USE [SendMessage]
GO
/****** Object: StoredProcedure [dbo].[pages] Script Date: 07/09/2015 13:46:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[pages]
(
@tbname nvarchar(100), --要分页显示的表名
@FieldKey nvarchar(1000), --用于定位记录的主键(惟一键)字段,可以是逗号分隔的多个字段
@PageCurrent int=1, --要显示的页码
@PageSize int=10, --每页的大小(记录数)
@FieldShow nvarchar(1000)='', --以逗号分隔的要显示的字段列表,如果不指定,则显示所有字段
@FieldOrder nvarchar(1000)='', --以逗号分隔的排序字段列表,可以指定在字段后面指定DESC/ASC
@WhereString nvarchar(1000)=N'' --查询条件
)
AS
begin
IF ISNULL(@FieldKey,N'')=''
BEGIN
RAISERROR(N'分页处理需要主键(或者惟一键)',1,16)
RETURN
END
IF ISNULL(@PageCurrent,0)1 SET @PageCurrent=1
IF ISNULL(@PageSize,0)1 SET @PageSize=10
IF ISNULL(@FieldShow,N'')=N'' SET @FieldShow=N'*'
IF ISNULL(@FieldOrder,N'')=N''
SET @FieldOrder=N''
ELSE
SET @FieldOrder=N'ORDER BY '+LTRIM(@FieldOrder)
IF ISNULL(@WhereString,N'')=N''
SET @WhereString=N''
ELSE
SET @WhereString=N'WHERE '+@WhereString+N''
--计算分页显示的TOPN值
DECLARE @TopN varchar(20),@StartRecord varchar(20),@EndRecord varchar(20)
SELECT @TopN=@PageSize,
@StartRecord=(@PageCurrent-1)*@PageSize+1,
@EndRecord=(@PageCurrent-1)*@PageSize+@PageSize
--第一页直接显示
IF @PageCurrent=1
EXEC(N'SELECT TOP '+@TopN
+N' '+@FieldShow
+N' FROM '+@tbname
+N' '+@WhereString
+N' '+@FieldOrder)
ELSE
EXEC(N'with temptbl as(
select ROW_NUMBER() Over('+@FieldOrder+') as row, '+@FieldKey+' from '+@tbname+N' '+@WhereString+')
select '+@FieldShow+' from (select B.* from (select '+@FieldKey+' from temptbl where row between '+@StartRecord+' and '+@EndRecord+')A left join '+@tbname+' B on A.'+@FieldKey+'=B.'+@FieldKey+')C')
END