SqlServer存储过程(增删改查)
* IDENT_CURRENT 返回为任何会话和任何作用域中的特定表最后生成的标识值。
CREATE PROCEDURE [dbo].[PR_NewsAffiche_AddNewsEntity]
(
@NewsTitle varchar(200),
@NewsContent varchar(4000),
@Creator varchar(50),
@LastNewsId int output,
@DepartId int
)
AS
BEGIN
SET NOCOUNT ON; insert into tbNewsAffiche(Title,Content,Creator,CreateTime,Updator,UpdateTime,DepartId)
values(@NewsTitle,@NewsContent,@Creator,getdate(),@Creator,getdate(),@DepartId) set @LastNewsId = IDENT_CURRENT('tbNewsAffiche')
END
存储过程方法体内定义及赋值:
declare @recordCount int
set @recordCount=0
====================================
增加:
存储过程
USE [testdb]
GO
/****** 对象: StoredProcedure [dbo].[PR_QueueNewsAffiche_AddQueueNews] 脚本日期: 11/01/2013 15:40:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO CREATE proc [dbo].[PR_QueueNewsAffiche_AddQueueNews](@Content nvarchar(500),@NewsAfficheId int,@BeginTime datetime,@EndTime datetime,@Creator varchar(50),@CreateTime datetime,@Updator varchar(50),@UpdateTime datetime)
as
insert into tbQueueNewsAffiche([Content],NewsAfficheId,BeginTime,EndTime,Creator,CreateTime,Updator,UpdateTime) values(@Content,@NewsAfficheId,@BeginTime,@EndTime,@Creator,getdate(),@Updator,getdate());
对应DAL层后台代码:
/// <summary>
/// 添加
/// </summary>
/// <param name="newsInfo"></param>
/// <returns></returns>
public int Add(QueueNewsAffiche_NewsInfo newsInfo)
{
IDataParameter[] paramArray = new IDataParameter[]{
Db.GetParameter("@Content",DbType.String,newsInfo.Content),
Db.GetParameter("@NewsAfficheId",DbType.Int32,newsInfo.NewsAfficheId),
Db.GetParameter("@BeginTime",DbType.DateTime,newsInfo.BeginTime),
Db.GetParameter("@EndTime",DbType.DateTime,newsInfo.EndTime),
Db.GetParameter("@Creator",DbType.String,newsInfo.Creator),
Db.GetParameter("@CreateTime",DbType.DateTime,newsInfo.CreateTime),
Db.GetParameter("@Updator",DbType.String,newsInfo.Updator),
Db.GetParameter("@UpdateTime",DbType.DateTime,newsInfo.UpdateTime)
};
int returnValue = 0;
try
{
returnValue = Db.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "PR_QueueNewsAffiche_AddQueueNews", paramArray);
}
catch (System.Exception e)
{
LogHelper.Error("添加时出错" + e.ToString());
}
return returnValue;
}
=======================================
删除:
存储过程
USE [testdb]
GO
/****** 对象: StoredProcedure [dbo].[PR_QueueNewsAffiche_Delete] 脚本日期: 11/01/2013 15:46:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO CREATE PROCEDURE [dbo].[PR_QueueNewsAffiche_Delete](@Id int,@Result int output) //@Result为输出
AS
BEGIN
IF EXISTS(SELECT 1 FROM tbQueueNewsAffiche //判断是否有数据SELECT top 1 FROM tbQueueNewsAffiche WHERE Id = @Id 不存在用not exists
WHERE Id = @Id)
BEGIN
DELETE FROM tbQueueNewsAffiche
WHERE Id = @Id
set @Result=1;
END
else
begin
set @Result =0;
end
END
对应DAL层代码:
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int DeleteById(int id)
{
IDataParameter[] paramArray = new IDataParameter[]{
Db.GetParameter("@Result",DbType.Int32,ParameterDirection.Output), //输出参数
Db.GetParameter("@Id",DbType.Int32,id)
};
try
{
int effectedRows = Db.ExecuteSPNonQuery(ConnectionString, "PR_QueueNewsAffiche_Delete", paramArray);
int result = Field.GetOutPutParam(paramArray[0], 0);
return result;
}
catch (System.Exception ex)
{
Log.WriteUserLog("删除失败" + ex.ToString(), 0, 0, 0);
return 0;
}
}
================================
修改:
存储过程:
USE [testdb]
GO
/****** 对象: StoredProcedure [dbo].[PR_QueueNewsAffiche_Update] 脚本日期: 11/04/2013 10:54:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO CREATE PROCEDURE [dbo].[PR_QueueNewsAffiche_Update]
(
@Id int,
@Content nvarchar(500),
@BeginTime datetime,
@EndTime datetime,
@Updator varchar(50)
)
AS
BEGIN
SET NOCOUNT ON; 这一句要注意:作用是不返回受影响的行数,一般做更新的不要设置,方便获取到返回的行数来判断是否更新成功。 update tbQueueNewsAffiche
set
[Content]=@Content,
BeginTime=@BeginTime,
EndTime=@EndTime,
Updator=@Updator,
UpdateTime=getdate()
where Id=@Id END
对应DAL层代码:
/// <summary>
/// 更新
/// </summary>
/// <param name="id">排队新闻id</param>
/// <param name="content"></param>
/// <param name="beginTime"></param>
/// <param name="endTime"></param>
/// <param name="updator"></param>
/// <returns></returns>
public int Update(int id,string content,DateTime beginTime,DateTime endTime,string updator)
{
IDataParameter[] paramArray = new IDataParameter[] {
Db.GetParameter("@Id",DbType.Int32,id),
Db.GetParameter("@Content",DbType.String,content),
Db.GetParameter("@BeginTime",DbType.DateTime,beginTime),
Db.GetParameter("@EndTime",DbType.DateTime,endTime),
Db.GetParameter("@Updator",DbType.String,updator)
}; int returnValue = 0;
try
{
returnValue = Db.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "PR_NewsAfficheQueue_Update", paramArray);
}
catch (System.Exception ex)
{
LogHelper.Error("更新时出错{PR_NewsAfficheQueue_Update}" + ex.ToString());
}
return returnValue;
}
=================================
查询:
存储过程
USE [testdb]
GO
/****** 对象: StoredProcedure [dbo].[PR_QueueNewsAffiche_GetAllNews] 脚本日期: 11/01/2013 15:53:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO CREATE proc [dbo].[PR_QueueNewsAffiche_GetAllNews](@NewsAfficheId int)
as
begin
SET NOCOUNT ON;
select
Id,
[Content],
NewsAfficheId,
BeginTime,
EndTime,
Creator,
CreateTime,
Updator,
UpdateTime
from dbo.tbQueueNewsAffiche where NewsAfficheId=@NewsAfficheId order by BeginTime
end
对应DAL代码:
/// <summary>
/// 查询所有排队新闻
/// </summary>
/// <returns></returns>
public List<QueueNewsAffiche_NewsInfo> GetList(int newsAfficheId)
{
IDataParameter[] paramArray = new IDataParameter[]{
Db.GetParameter("@NewsAfficheId",DbType.Int32,newsAfficheId)
}; List<QueueNewsAffiche_NewsInfo> list = null;
try
{
using (IDataReader reader = Db.ExecuteSPReader(ConnectionString, "PR_QueueNewsAffiche_GetAllNews", paramArray))
{
list = new List<QueueNewsAffiche_NewsInfo>();
while (reader.Read())
{
QueueNewsAffiche_NewsInfo newsInfo = new QueueNewsAffiche_NewsInfo();
IDataRecord rec = reader as IDataRecord; newsInfo.Id = Field.GetInt32(rec, "Id");
newsInfo.Content = Field.GetString(rec, "Content");
newsInfo.NewsAfficheId = Field.GetInt32(rec, "NewsAfficheId");
newsInfo.BeginTime = Field.GetDateTime(rec, "BeginTime");
newsInfo.EndTime = Field.GetDateTime(rec, "EndTime");
newsInfo.Creator = Field.GetString(rec, "Creator");
newsInfo.CreateTime = Field.GetDateTime(rec, "CreateTime");
newsInfo.Updator = Field.GetString(rec, "Updator");
newsInfo.UpdateTime = Field.GetDateTime(rec, "UpdateTime");
list.Add(newsInfo);
}
}
}
catch (System.Exception ex)
{
LogHelper.Error("查询时出错" + ex.ToString());
} return list;
}
根据id查询
USE [testdb]
GO
/****** 对象: StoredProcedure [dbo].[PR_QueueNewsAffiche_GetNewsById] 脚本日期: 11/04/2013 13:44:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[PR_QueueNewsAffiche_GetNewsById]
(
@Id int
)
AS
BEGIN
SET NOCOUNT ON; select *
from tbQueueNewsAffiche
where Id=@Id
END
对应DAL层代码:
/// <summary>
/// 根据id查询
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public QueueNewsAffiche_NewsInfo GetQueueNewsById(int id)
{ IDataParameter[] paramArray = new IDataParameter[] {
Db.GetParameter("@Id",DbType.Int32,id)
};
QueueNewsAffiche_NewsInfo newsInfo = null;
try
{
using (IDataReader reader = Db.ExecuteSPReader(ConnectionString, "PR_NewsAfficheQueue_GetNewsById", paramArray))
{
while (reader.Read())
{
newsInfo = new QueueNewsAffiche_NewsInfo();
IDataRecord rec = reader as IDataRecord; newsInfo.Content = Field.GetString(rec, "Content");
newsInfo.BeginTime = Field.GetDateTime(rec, "BeginTime");
} }
}
catch (System.Exception ex)
{
LogHelper.Error("查询排队新闻时出错{PR_NewsAfficheQueue_GetNewsById}" + ex.ToString());
}
return newsInfo;
}
存储过程中执行SQL语句:
USE [BookSale]
GO
/****** 对象: StoredProcedure [dbo].[SP_SaleBookCustomAddress_GetCustomAddressByUserIdList_1_19882] 脚本日期: 01/16/2014 15:30:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO -- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
CREATE procedure [dbo].[SP_SaleBookCustomAddress_GetCustomAddressByUserIdList_1_19882]
(
@UserIdList nvarchar(max)
)
as
begin
exec('select * from SaleBookCustomAddress where UserId in ('+@UserIdList+') and Status=1') end
DAL获取上面存储过程获得的内容:
/// <summary>
/// 根据多个UserId批量获取地址实体列表
/// </summary>
/// <param name="userIdList"></param>
/// <returns></returns>
public List<Entity.Activity.SaleBookCustomAddress> GetActivityRosterByUserIdList(string userIdList)
{
IDataParameter[] par = new IDataParameter[] {
AdoHelper.GetParameter("UserIdList",DbType.String ,userIdList )
}; List<SaleBookCustomAddress> rtn = new List<SaleBookCustomAddress>();
try
{
using (IDataReader reader = AdoHelper.ExecuteReader(this.DefaultConnectionString, CommandType.StoredProcedure, "SP_SaleBookCustomAddress_GetCustomAddressByUserIdList_1_19882", par))
{
while (reader.Read())
{
SaleBookCustomAddress address = new SaleBookCustomAddress();
address.UserId = Convert.ToInt64(reader["UserId"]); UserDataAccess userDB = new UserDataAccess();
Users user = userDB.GetUserNickname(new int[] { Convert.ToInt32(address.UserId) })[0];
if (user != null)
{
address.NickName = user.UserName;
}
else
{
address.NickName = "";
}
address.CustomName = Field.GetString(reader, "CustomName");
address.Region = Field.GetString(reader, "Region");
address.Province = Field.GetString(reader, "Province");
address.City = Field.GetString(reader, "City");
address.Street = Field.GetString(reader, "Street");
address.Postcode = Field.GetString(reader, "Postcode");
address.MobileNo = Field.GetString(reader, "MobileNo");
address.FullTelNum = Field.GetString(reader, "TeleArea") + "-" + Field.GetString(reader, "Telephone") + "-" + Field.GetString(reader, "TeleExt");
if (address.FullTelNum == "--")
{
address.FullTelNum = "";
}
else
{
if (string.IsNullOrEmpty(Field.GetString(reader, "TeleExt")))
{
address.FullTelNum = Field.GetString(reader, "TeleArea") + "-" + Field.GetString(reader, "Telephone");
}
}
address.LastUpdateTime = Field.GetDateTime(reader, "LastUpdateTime"); rtn.Add(address);
}
}
}
catch (Exception ex)
{
Log.LogException(ex);
}
return rtn;
}
零碎补充:
@AboutTheAuthor varchar(max),
@RMBOriginPrice decimal(18,2), /*表示一共18位数字,其中包括2位小数点(整数部分则为16位)*/ decimal详解>>
@AuthorName varchar(100)='', /*参数赋初值 */
@RecordCount int=0 output /*赋初值的输出变量 */
select @RecordCount=count(1) from SaleBook where companyid=17 AS /*表示下面的为存储过程主体部分*/ /*@@表示全局变量(内置系统变量)、获取最新的主键id select @@rowcount受影响的行数 */
SELECT @@identity exec(@sql+@where+' ORDER BY CreateTime DESC') /*执行sql语句*/ WITH Mem_SALEBOOK_Book AS /*WITH的用法*/
(
SELECT bookId
FROM bookView V
WHERE CompanyId in ( select Item from dbo.fn_Split(@CompanyId,',') )
and BookId= CASE @SearchType WHEN 'bookid' THEN @SearchValue ELSE BookId END /*CASE...WHEN语法 */
and BookName like CASE @SearchType WHEN 'bookname' THEN @SearchValue ELSE BookName END
) SELECT M.*, SC.CompanyName as CompanyName FROM
Mem_SALEBOOK_Book MM with (nolock)
inner join bookView M on MM.BookId=M.BookId
left join SaleCompany SC on M.CompanyId=SC.CompanyId
站内导航:
站外扩展:
SqlServer存储过程(增删改查)的更多相关文章
- NX二次开发-NX访问SqlServer数据库(增删改查)C#版
版本:NX9+VS2012+SqlServer2008r2 以前我写过一个NX访问MySQL数据库(增删改查)的文章https://www.cnblogs.com/nxopen2018/p/12297 ...
- 用C# sqlserver实现增删改查
using System.Data;using System.Data.SqlClient;//先打开两个类库文件SqlConnection con = new SqlConnection(); // ...
- SpringMVC+SpringJdbc+SQLServer+EasyUI增删改查
前言 前天用SpringJdbc连接了一把SQLServer,早上起来用SpringMVC+SpringJdbc+EasUI写了个增删改查的demo,主要是熟悉下SpringMVC相关知识点,如vie ...
- SQLServer数据库增删改查
一.数据库定义 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库.数据库的操作分为两种形式:一种是直接在数据库管理工具图形化界面进行操作:一种是使用数据库脚本进行操作,数据库脚本可 ...
- 连接SQLServer的增删改查方法代码
在Visual C++中用ADO进行数据库编程 1. 生成应用程序框架并初始化OLE/COM库环境 创建一个标准的MFC AppWizard(exe)应用程序CADOConnection,然后在使用A ...
- sqlserver的增删改查
select*from shuiguo 查询表 且小于等于7的范围) select distinct name from shuiguo--去除重复,只针对一列 select * from shui ...
- C#学习笔记(3)——操作sqlserver数据库增删改查
说明(2017-5-25 16:29:35): 1. VS2010,视图->服务器资源管理器->数据连接->右键添加连接->服务器名(本机可以用点)->选择数据库-> ...
- C#中对sqlserver进行增删改查操作(简单易懂)
1.添加引用using System.Data;using System.Data.SqlData; 2.建立于数据库的连接,建议将它做成一个方法,方便多次利用.string sqlconnectio ...
- 关于MVC工厂模式的增删改查sql存储过程
这里MVC中用到了反射,工厂,泛型,接口 在搭建框架的时候,除了MVC的三层以外,还有泛型的接口层和工厂层 下面是dal层调用sql存储过程,增删改查,dal层继承了接口层,实现了接口层里面的方法 1 ...
- 设置Sql server用户对表、视图、存储过程、架构的增删改查权限
根据数据库Schema限制用户对数据库的操作行为 授予Shema dbo下对象的定义权限给某个用户(也就是说该用户可以修改架构dbo下所有表/视图/存储过程/函数的结构) use [Your DB N ...
随机推荐
- expect ssh 自动登录 example
#!/usr/bin/expect -f set ip [lindex $argv ] set port [lindex $argv ] set username [lindex $argv ] se ...
- 【刷题】BZOJ 1061 [Noi2008]志愿者招募
Description 申奥成功后,布布经过不懈努力,终于成为奥组委下属公司人力资源部门的主管.布布刚上任就遇到了一个难题:为即将启动的奥运新项目招募一批短期志愿者.经过估算,这个项目需要N 天才能完 ...
- 【BZOJ1914】数三角形(组合数,极角排序)
[BZOJ1914]数三角形(组合数,极角排序) 题面 BZOJ权限题 良心洛谷 题解 这种姿势很吼啊,表示计算几何啥的一窍不通来着. 题目就是这样,正难则反,所以我们不考虑过原点的三角形, 反过来, ...
- Alpha 冲刺 —— 十分之五
队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 协助测试的进行 测试项目运行的服务器环境 ...
- 【BZOJ4004】【JLOI2015】装备购买
Description 脸哥最近在玩一款神奇的游戏,这个游戏里有 n 件装备,每件装备有 m 个属性,用向量zi(aj ,.....,am) 表示 (1 <= i <= n; 1 < ...
- #define后面只带有一个标识符
经常看到有#define后只有一个标识符的语句,这样是做宏开关用 宏定义编译前会被编译器进行替换,只有一个标识符的情况,如果在代码里使用了这个标识符,会被替换为空,也就是相当于没加. 用来做编译开关的 ...
- MyBatis.1入门篇
一:简介 MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动.创建connection.创建statem ...
- java 操作命令行
目的:用java进行调用ab压测 window: cmd ab.exe linux: sh ab.sh 命令: abs -n 500 -c 10 https://www.baidu.com/ > ...
- [CQOI2012] 交换棋子 (费用流)
$pdf\space solution$ link #include<iostream> #include<cstring> #include<cstdio> ...
- 【题解】新型城市化 HAOI2017 网络流 二分图最大匹配 强连通分量
Prelude 好,HAOI2017终于会做一道题了! 传送到洛谷:→_→ 传送到LOJ:←_← 本篇博客链接:(●'◡'●) Solution 首先要读懂题. 考场上我是这样想的QAQ. 我们把每个 ...