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
站内导航:
站外扩展: