復制代碼 代碼如下:
/*
數據庫分頁存儲過程,支持倒序和升序
參數說明:
@tablename:為搜索表名
@tablefield:為表的字段,約定為表的主鍵,
@where:為搜索表名,要顯示所有記錄請設為"1=1"
@orderby:為搜索結果排序,如order by id desc
@fieldlist:為字段列表,如userid, username
@curpage:當前頁碼
@page_record:每頁記錄條數
@Sort:排序標識(如果是倒序排,參數值為desc,為升序,參數值為asc,跟orderby參數是對應的)
結果: 返回表tablename中滿足條件where的第curpage頁的page_record條記錄,結果按orderby排序
*/
CREATE PROCEDURE proc_CommonPaging
@tablename varchar(100),
@tablefield varchar(20),
@where varchar(5000),
@orderby varchar(500),
@fieldlist varchar(1000),
@curpage int,
@page_record int,
@sort varchar(8)
AS
BEGIN
DECLARE @cmd varchar(8000)
DECLARE @uprecord int
DECLARE @Op varchar(2) -- 操作符
DECLARE @max_min varchar(4) -- 最大/最小計算
SET @op = '<'
SET @max_min = 'MIN'
IF @sort = 'asc'
BEGIN
SET @Op = '>'
SET @max_min = 'MAX'
END
SET @uprecord=@curpage * @page_record
IF @curpage = 0
SET @cmd = 'SELECT TOP '+cast(@page_record AS NVARCHAR)+' '+@fieldlist+' FROM '+@tablename+' WHERE '+@where+' '+@orderby
ELSE
SET @cmd = 'SELECT TOP '+cast(@page_record AS NVARCHAR)+' '+@fieldlist+' FROM '+@tablename+' WHERE '+@where+' AND '+@tablefield+'
'+@op+' (SELECT '+@max_min+'('+@tablefield+') FROM (SELECT TOP '+cast(@uprecord AS NVARCHAR)+' '+@tablefield+' FROM '+@tablename+' WHERE
'+@where+' '+@orderby+') AS TmpTbl ) AND '+@where+' '+@orderby
SET @cmd = @cmd + '; SELECT COUNT(*) FROM '+@tablename+' WHERE '+@where
EXEC(@cmd)
PRINT(@cmd)
END
GO