create procedure getrecordfrompage
@tblname varchar(255), -- 表名
@fldname varchar(255), -- 欄位名
@pagesize int = 10, -- 頁尺寸
@pageindex int = 1, -- 頁碼
@iscount bit = 0, -- 返回記錄總數, 非 0 值則返回
@ordertype bit = 0, -- 設定排序型別, 非 0 值則降序
@strwhere varchar(1000) = '' -- 查詢條件 (注意: 不要加 where)
asdeclare @strsql varchar(6000) -- 主語句
declare @strtmp varchar(100) -- 臨時變數
declare @strorder varchar(400) -- 排序型別
if @ordertype != 0
begin
set @strtmp = "<(select min"
set @strorder = " order by [" + @fldname +"] desc"
endelse
begin
set @strtmp = ">(select max"
set @strorder = " order by [" + @fldname +"] asc"
endset @strsql = "select top " + str(@pagesize) + " * from ["
+ @tblname + "] where [" + @fldname + "]" + @strtmp + "(["
+ @fldname + "]) from (select top " + str((@pageindex-1)*@pagesize) + " ["
+ @fldname + "] from [" + @tblname + "]" + @strorder + ") as tbltmp)"
+ @strorder
if @strwhere != ''
set @strsql = "select top " + str(@pagesize) + " * from ["
+ @tblname + "] where [" + @fldname + "]" + @strtmp + "(["
+ @fldname + "]) from (select top " + str((@pageindex-1)*@pagesize) + " ["
+ @fldname + "] from [" + @tblname + "] where " + @strwhere + " "
+ @strorder + ") as tbltmp) and " + @strwhere + " " + @strorder
if @pageindex = 1
begin
set @strtmp = ""
if @strwhere != ''
set @strtmp = " where " + @strwhere
set @strsql = "select top " + str(@pagesize) + " * from ["
+ @tblname + "]" + @strtmp + " " + @strorder
endif @iscount != 0
set @strsql = "select count(*) as total from [" + @tblname + "]"
exec (@strsql)
go
萬能儲存過程分頁
引數說明 tblname 需要查詢的表名。如圖書表tblbooks 如果是多表 圖書表關聯圖書分類表 則寫成 tblbooks inner join tblbooktypes on tblbooks.bookid tblbooktypes.bookid fldname 主鍵欄位名 bookid li...
SQL萬能儲存過程分頁
alter proc dbo proc pager tablename varchar 50 表名 refieldsstr varchar 200 欄位名 全部欄位為 orderstring varchar 200 排序字段 必須 wherestring varchar 500 n 條件語句 不用加...
SqlServer萬能分頁儲存過程
alter proc sp hangkong table nvarchar 200 表,字段,條件,field nvarchar 2000 欄位 where nvarchar 2000 條件 order nvarchar 200 排序所需要的的 pagesize int,每頁顯示的個數 pagenu...