SQL Server 分页存储过程

USE [ReportServerTempDB]
GO
CREATE PROCEDURE [dbo].[SeachTablePage]
(
	@TableName VARCHAR(200),	-- 表名
	@Fileds VARCHAR(500),		-- 查询的字段
	@OrderFiled VARCHAR(100),	-- 排序字段
	@IsDesc BIT ,				-- 是否降序排序
	@WhereString VARCHAR(2000), -- 查询字段
	@PageIndex INT ,			-- 当前页数
	@PageSize INT ,				-- 每页条数
	@TotalRecord INT OUTPUT		-- 返回总条数
)
AS
BEGIN
	DECLARE @OrderString VARCHAR(500)
	
	IF(@PageIndex IS NULL OR @PageIndex <= 0)
	BEGIN
		SET @PageIndex = 1
	END
	
	IF(@PageSize IS NULL OR @PageSize <= 0)
	BEGIN
		SET @PageSize = 10
	END
	
	DECLARE @StartRowID INT
	DECLARE @EndRowID INT
	SET @StartRowID = (@PageIndex - 1) * @PageSize + 1
	SET @EndRowID = @PageIndex * @PageSize
	
	IF (@WhereString is null OR @WhereString = '')
	BEGIN
	 	SET @WhereString = '1 = 1'
	END
	
	IF (@OrderFiled IS NULL OR @OrderFiled = '')
	BEGIN
		SET @OrderFiled = 'CreateDate'
	END
	
	IF (@IsDesc IS NULL OR @IsDesc = 1)
	BEGIN
		SET @OrderString = @OrderFiled + ' DESC'
	END
	ELSE
	BEGIN
		SET @OrderString = @OrderFiled + ' ASC'
	END
	
	DECLARE @TotalSQL NVARCHAR(2000)
	SET @TotalSQL = 'SELECT @Total = COUNT(*) FROM ' + @TableName + ' WHERE ' + @WhereString + ''
	EXEC sp_executesql @TotalSQL , N'@Total BIGINT OUT' , @TotalRecord OUTPUT -- 返回总记录数

	DECLARE @SelectSQL NVARCHAR(3000)
	IF(@TotalRecord <= @PageSize AND @PageIndex = 1)
	BEGIN
		SET @SelectSQL = 'SELECT ' + @Fileds + ' FROM ' + @TableName + ' WHERE ' + @WhereString + ' ORDER BY ' + @OrderString
	END
	ELSE
	BEGIN
		SET @SelectSQL = 'SELECT row_number() OVER (ORDER BY ' + @OrderString + ') AS RowId,' + @Fileds + ' FROM ' + @TableName + ' WHERE ' + @WhereString
		SET @SelectSQL = 'SELECT * FROM (' + @SelectSQL + ') AS tab WHERE RowId BETWEEN ' + ltrim(STR(@StartRowID)) + ' AND ' + ltrim(STR(@EndRowID)) + ''
	END
	print @SelectSQL
	EXEC (@SelectSQL)
END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值