存儲過程--查詢:
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_Test')) --判斷存儲過程是否存在, BEGIN drop proc Page_Test --存在則刪除然后重建。 END GO CREATE PROC Page_Test --創建存儲過程 @PageIndex INT, @PageSize INT, @Name nvarchar (50), @TypeId nvarchar (50) AS BEGIN --開始 DECLARE @PageHome INT ; --起始頁 DECLARE @condition nvarchar (2000) ;--WHERE條件 SET @PageHome = @PageIndex * @PageSize ; SET @condition = ' where 1=1 ' ; IF (@Name <> '') SET @condition =@condition + ' and Name like ''%' +@Name + '%''' ; IF (@TypeId <> '') SET @condition =@condition + ' and TypeId = ' +@TypeId + ''; EXEC (' select top '+@PageSize+' * from (select row_number() over(order by Id asc) as rownumber,* from [Test] '+@condition+') AS A where rownumber > '+@PageHome+' select count(*) as rows from [Test] '+@condition+' ') ; END ; --結束
調用方式:
EXEC Page_Test 1000,1000,'',''
調用結果:(運行速度很快160W數據 0.3秒查詢完成)