/**
if exists (select * from sysobjects where name='page_sort')
drop proc page_sort
**/create proc page_sort(
@name nvarchar(100)='', --表名,如 pinyin
@pagesize int, --每頁的記錄數,預設為 10
@curpage int=1, --表示當前頁 1
@keyfield nvarchar(100)='', --關鍵欄位名,預設為 id,該欄位要求是表中的索引 或 無重複和不為空的字段
@keyascdesc nvarchar(4)='', --關鍵字的公升、降序,預設為公升序 asc , 降序為 desc
@fields nvarchar(500)='*', --所選擇的列名,預設為全選
@condition nvarchar(3000)='', --where 條件,預設為空
@order nvarchar(200)='' --排序條件,預設為空
) with encryption as
if @name = ''
begin
raiserror('請指定表名!',11,1)
return
endif @pagesize <=0 or @curpage <0
begin
raiserror('當前頁數和每頁的記錄數都必須大於零!',11,1)
return
endif @keyascdesc = 'desc'
set @keyascdesc = '<'
else
set @keyascdesc = '>'
if @condition <> ''
set @condition = ' where ' + @condition
declare @sql nvarchar(3000)
set @sql = ''
if @curpage = 1
set @sql = @sql + 'select top ' + cast(@pagesize as nvarchar(20)) + ' ' + @fields + ' from ' + @name + @condition + ' ' + @order
else
begin
declare @itopnum int
set @itopnum = @pagesize * (@curpage - 1)
set @sql = @sql + 'declare @slastvalue nvarchar(100)' + char(13)
set @sql = @sql + 'select top ' + cast(@itopnum as nvarchar(20)) + '@slastvalue=' + @keyfield + ' from ' + @name + @condition + ' ' + @order + char(13)
declare @condition2 nvarchar(3000)
if @condition = ''
set @condition2 = ' where ' + @keyfield + @keyascdesc + '@slastvalue '
else
set @condition2 = ' and ' + @keyfield + @keyascdesc + '@slastvalue '
set @sql = @sql + 'select top ' + cast(@pagesize as nvarchar(20)) + ' ' + @fields + ' from ' + @name + @condition + @condition2 + @order
endexecute sp_executesql @sql
go呼叫:
exec page_sort 'venshop_sub',20,1,'sub_id','desc','*', 'sub_name=''zkarron''' ,'order by sub_date desc'
SQL SERVER分頁儲存過程
使用儲存過程寫乙個分頁查詢 select from t users gocreate proc usp getdatafy pagesize int 10,每頁記錄條數 定義變數並賦初始值 pageindex int 1,當前要檢視第幾頁的記錄 sumcount int output,總的記錄條數 ...
SqlServer分頁儲存過程
高效分頁語句 1 row number select from select row number over order byrpid as rowfrom ou rolepermission as twheret.row 0 andt.row 10 2,top 分頁查詢 select top 10...
sql server 分頁儲存過程
sql server 分頁儲存過程,在網上找了很多,但是都不能用或者不能很好的用,特別綜合大家的智慧型,自己寫了乙個,而且通過visual studio除錯,通過實際資料測試 set ansi nulls on set quoted identifier on go alter procedure ...