sqlserver 單表(視圖)通用分頁存儲過程sql
create procedure proc_getpage @table_name varchar(100), --表名(視圖) @select_fields varchar(1000)=' * ', --須要返回的列 @page_size int=10, --頁尺寸,若是爲0則表示返回全部行,不分頁 @page_index int=1, --頁碼 @sort_field varchar(50)='', --排序字段 @order_type nvarchar(10)='desc', --排序類型, asc|desc @str_where varchar(max)='' --查詢條件(注意: 不要加 where) as begin declare @select_sql varchar(max) --主語句 declare @count_sql varchar(max) --獲取總記錄數語句 declare @order_sql varchar(400) --排序子語句 if(@str_where!='') begin set @count_sql='select count(*) as total from ' + @table_name + ' where ' + @str_where end else begin set @count_sql='select count(*) as total from ' + @table_name end set @order_sql=' order by ' + @sort_field + ' ' + @order_type if(@page_size=0) begin if(@str_where!='') begin set @select_sql='select ' + @select_fields + ' from ' + @table_name + ' where ' + @str_where + ' ' + @order_sql end else begin set @select_sql='select ' + @select_fields + ' from ' + @table_name + ' ' + @order_sql end end else begin set @select_sql='select * from (select row_number() over(' + @order_sql + ') as rowNo,' + @select_fields + ' from ' + @table_name if(@str_where!='') begin set @select_sql+=' where ' + @str_where end set @select_sql+=') as ' + @table_name + ' where rowNo between ' + cast(((@page_index-1)*@page_size+1) as varchar) + ' and ' + cast((@page_index*@page_size) as varchar) end exec(@count_sql) exec(@select_sql) end