存儲過程--查詢:
if (exists (select * from sys.objects where name = 'GetUser')) drop proc GetUser --判斷存儲過程是否存在,存在則刪除然后重建。 go create proc GetUser --創建存儲過程 GetUser @Id int --參數 as set nocount on; --不返回計數,提高應用程序性能 begin --開始 select * from [dbo].[User] where Id=@Id --執行sql語句 end;--結束
調用存儲過程
EXEC GetUser 1;
執行結果
存儲過程--修改:
if (exists (select * from sys.objects where name = 'UpdateUser')) drop proc UpdateUser --判斷存儲過程是否存在,存在則刪除然后重建。 go create proc UpdateUser --創建存儲過程 GetUser @Id int, --參數 @Name varchar(255),--參數 @Sex int, --參數 @Age int, --參數 @Birthday date --參數 as set nocount on; --不返回計數,提高應用程序性能 begin --開始 UPDATE [dbo].[UserInfo] SET [Name]=@Name,[Sex]=@Sex, [Age]=@Age,[Birthday]=@Birthday WHERE ([Id]=@Id) --執行sql語句 end;--結束
調用存儲過程:
EXEC UpdateUser 1,'趙大1',2,222,'1994-07-16 11:36:27';
執行結果:
存儲過程分頁
if (exists (select * from sys.objects where name = 'Page_UserInfo')) drop proc Page_UserInfo --判斷存儲過程是否存在,存在則刪除然后重建。 go create proc Page_UserInfo --創建存儲過程 @name nvarchar(255),--用戶名 @pageindex int,--第幾頁 @pagesize int--一頁多少條 as set nocount on; --不返回計數,提高應用程序性能 begin --開始 declare @pagebefore int;--創建頁數 declare @pagerear int;--創建頁數 declare @condition nvarchar(2000); --創建where條件 set @pagebefore=@pagesize*@pageindex; --起始頁 set @pagerear=@pagebefore+@pagesize;--結束頁 set @condition=' where 1=1 '; if(@name<>'') set @condition=@condition+' and name like ''%'+@name+'%'''; --創建一個虛擬表插入UserInfo表數據 --獲取分頁數據 --獲取總數 exec(' declare @table table( iid int identity, Id int, Name nvarchar(20), Sex int, Age int, Birthday datetime ) insert @table select * from UserInfo '+@condition+' order by Id desc select * from @table where iid>'+@pagebefore+' and iid<='+@pagerear+' select count(*) as rows from @table;'); end;--結束
調用方式:
EXEC Page_UserInfo '' ,1,10