包括了: 分页 和 排序
USE [DataBaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [dbo].[procedureName]
@srcTableName Nvarchar(50), --视图或表名
@condition varchar(1000), --查询条件
@pageSize int = 10, --每页长度(1~n)
@pageIndex int = 1, --页码(1~n)
@orderBy Nvarchar(50), --排序方式,必须为查询结果中的字段名
@isDesc Nvarchar(50) , --倒序还是正序
@hascount int = 0 --查询结果是否带总行数(0:不带;1:带)
AS
begin
-- 参数容错
if (@pageIndex <= 0)
begin
set @pageIndex = 1
end
declare @select varchar(200)
if (@hascount = 0)
begin
set @select = ' select * ' ;
end
else if ( @hascount = 1 )
begin
set @select = ' select *,(select count(row_number) from SearchResult as count) ';
end
declare @sql varchar(6000)
set @sql=
' with SearchResult as
(
select row_number() over (order by ' + @orderBy + ' ' + @isDesc + ') as row_number , 其它所需字段
from ' + @srcTableName + ' ' + @condition +
' ) '
+ @select + ' from SearchResult where row_number > ' + cast (@pageSize*(@pageIndex-1) as varchar(50)) +
' and row_number <= ' + cast (@pageSize*(@pageIndex) as varchar(50)) +
' order by ' + @orderBy + ' ' + @isDesc
print @sql
exec(@sql)
end
GO