1 -- CTE 分页 2 -- 支持多表级联 , 指定字段输出 , 多表多字段复杂排序与过滤 3 -- 原理是把 每条记录加上了分页的页码,然后按页面去读取 4 -- 按照@StrConditions筛选和@StrOrder排序 使用ROW_NUMBER()得出 rowid 5 -- rowid / PageSize = 当前记录的所在页码 , 加入当前记录 6 7 CREATE PROCEDURE [ dbo ] . [ sp_CTE ] ( 8 @TableName varchar ( 500 ) , -- TableName 9 @TableFeilds varchar ( 2000 ) = ' * ' , -- TableFeilds default * 10 @PageSize int , -- PageSize 11 @PageIndex int , -- PageIndex 12 @OrderColumName varchar ( 1000 ) = null , -- Order default null 13 @IsAsc bit = 1 , -- ASC : 1 / DESC : 0 , if OderColumName(prior) is empty then order by @PK @IsAsc 14 @PK varchar ( 100 ) , -- PK 15 @Conditions varchar ( 1000 ) = null -- where default null 16 ) 17 AS 18 SET NOCOUNT ON ; 19 20 declare @StrSql nvarchar ( 4000 ) 21 declare @StrOrder nvarchar ( 1000 ) 22 declare @StrCte nvarchar ( 3000 ) 23 declare @StrConditions nvarchar ( 1000 ) 24 25 -- Oder by 26 if ( @OrderColumName is null or @OrderColumName = '' ) 27 begin 28 -- PK ASC/DESC 29 if @IsAsc = 1 30 set @StrOrder = ' order by ' + @PK + ' asc ' 31 else 32 set @StrOrder = ' order by ' + @PK + ' desc ' 33 end 34 else 35 set @StrOrder = ' order by ' + @OrderColumName 36 37 -- Where 38 if ( @Conditions is Not null And @Conditions <> '' ) 39 set @StrConditions = ' where ' + @Conditions 40 else 41 set @StrConditions = '' 42 43 -- CTE 44 set @StrCte = ' with Table_CET 45 as 46 ( 47 select 48 CEILING( 49 (ROW_NUMBER() OVER ( ' + @StrOrder + ' ))/ ' + str ( @PageSize ) + ' 50 ) as page_num, ' + @TableFeilds + ' 51 from ' + @TableName + @StrConditions + ' 52 ) 53 ' ; 54 55 set @StrSql = @StrCte + ' select * from Table_CET where page_num = ' + str ( @PageIndex ) ; 56 57 -- debug 58 print @StrSql 59 60 -- exec sql 61 begin 62 exec sp_executesql @StrSql ; 63 end 64