1 --分頁查詢
2 alter proc ShowInfo 3 @Table nvarchar(50),--表.視圖
4 @PageSize int,--每頁顯示數量
5 @PageIndex int,--當前顯示頁碼
6 @Conditions nvarchar(300),--篩選條件
7 @Pages int output--返回總共有多少頁
8 as
9 declare @start int ,--當前頁開始顯示的No
10 @end int,--當前頁結束顯示的No
11 @Context nvarchar(1024), --動態sql語句
12 @pkey nvarchar(10)--主鍵或索引
13 set @start=(@PageIndex-1)+1
14 set @end=@start+@PageSize-1
15 set @pkey=index_col(@Table,1,1)--獲取主鍵,或索引
16 --通過條件將符合要求的數據匯聚到臨時表#temp上
17 set @Context='select row_number() over(order by '+@pkey+') as [No],* into #temp from '+@Table
18 --判斷是否有篩選條件傳入
19 if(@Conditions is not null) 20 set @Context=@Context+' where '+@Conditions
21 --通過查詢#temp 表實現分頁.
22 set @Context=@Context+' select * from #temp where No between '+cast(@start as nvarchar(4))+' and '+cast(@end as nva rchar(4)) 23 --返回出總共可以分成多少頁
24 set @Context=@Context+' declare @count int select @count=count(*) from #temp set @Pages= @count/'+cast(@PageSi ze as nvarchar(4))+' if(@count%'+cast(@PageSize as nvarchar(4))+'<>0) set @Pages=@Pages+1 '
25
26 exec sp_executesql @Context,N'@Pages int output', @Pages output 27 -- sp_executesql @動態sql語句,@動態sql語句中需要的參數,@傳入動態sql語句參數的值(個人理解)
28 ---------------------------------------------------------------------------------------------------
29 declare @p int
30 exec ShowInfo 'Products',10,1,null, @p output 31 select @p