在專案中,會遇到查詢出的結果排序分頁的問題,可以有多種解決方法,乙個是利用開發工具提供的方法,例如.net visual studio中的gridview,就提供了排序,分頁功能。但如果情況複雜,我們可以把排序分頁放到儲存過程來完成。
以乙個簡單例子來說明問題:
table [reportfile]
field type
id int
name nvarchar(255)
content image
以id降序排序分頁的儲存過程如下:
create procedure [dbo].[reports_page]
@pagesize int, -------- 每頁行數
@pageindex int, -------- 制定頁數
@condition varchar(200) -------- 查詢條件
asbegin
declare @strsql varchar(5000)
if @pageindex = 1
begin
set @strsql = 'select top '
+ str(@pagesize)
+ ' [id],'
+ '[name],'
+ '[content] '
+ 'from [reports_page] '
+ 'where '
+ @condition
+ ' order by [reportarchiveglti_id] desc'
endelse
begin
set @strsql = 'select top '
+ str(@pagesize)
+ ' [id],'
+ '[name],'
+ '[content] '
+ 'from [reports_page] '
+ @condition
+ 'and ([id] < ('
+ 'select min([id]) from ( '
+ 'select top '
+ str((@pageindex-1)*@pagesize)
+ ' [id],'
+ '[name],'
+ '[content] '
+ 'from [reports_page] '
+ @condition
+ ' order by [reportarchiveglti_id] desc') as tbltmp ) )'
+ ' order by [reportarchiveglti_id] desc'
endexec(@strsql)
endgo
當呼叫儲存過程時,提供引數頁碼、每頁行數、條件即可。
在儲存過程中分頁
用儲存過程實現的分頁程式 鄒建 2003.09 引用請保留此資訊 呼叫示例 exec p show 地區資料 exec p show 地區資料 5,3,地區編號,地區名稱,助記碼 地區編號 if exists select from dbo.sysobjects where id object id...
分頁儲存過程 排序
用途 支援任意排序的分頁儲存過程 說明 create procedure up getrecordbypageorder tblname varchar 255 表名 fldname varchar 255 顯示欄位名 orderfldname varchar 255 排序欄位名 statfldna...
分頁儲存過程 分頁儲存過程
分頁儲存過程 alter proc dbo p pageshow pagesize int,每頁大小 currentpage int out,當前頁 housename nvarchar 50 房產名稱 totalcount int out,總記錄數 totalpage int out 總頁數 as...