通用的Sql存储过程

时间:2021-10-20 13:14:20
CREATE PROCEDURE [dbo].[P_ProcPager] (
@recordTotal INT OUTPUT, --输出记录总数
@viewName VARCHAR(800), --表名
@fieldName VARCHAR(800) = '*', --查询字段
@keyName VARCHAR(200) = 'Id', --索引字段
@pageSize INT = 20, --每页记录数
@pageNo INT =1, --当前页
@orderString VARCHAR(200), --排序条件
@whereString VARCHAR(800) = '1=1' --WHERE条件
)
AS
BEGIN
DECLARE @beginRow INT
DECLARE @endRow INT
DECLARE @tempLimit VARCHAR(200)
DECLARE @tempCount NVARCHAR(1000)
DECLARE @tempMain VARCHAR(1000)
--declare @timediff datetime set nocount on
--select @timediff=getdate() --记录时间 SET @beginRow = (@pageNo - 1) * @pageSize + 1
SET @endRow = @pageNo * @pageSize
SET @tempLimit = 'rows BETWEEN ' + CAST(@beginRow AS VARCHAR) +' AND '+CAST(@endRow AS VARCHAR) --输出参数为总记录数
SET @tempCount = 'SELECT @recordTotal = COUNT(*) FROM (SELECT '+@keyName+' FROM '+@viewName+' WHERE '+@whereString+') AS my_temp'
EXECUTE sp_executesql @tempCount,N'@recordTotal INT OUTPUT',@recordTotal OUTPUT --主查询返回结果集
SET @tempMain = 'SELECT * FROM (SELECT ROW_NUMBER() OVER (order by '+@orderString+') AS rows ,'+@fieldName+' FROM '+@viewName+' WHERE '+@whereString+') AS main_temp WHERE '+@tempLimit --PRINT @tempMain
EXECUTE (@tempMain)
--select datediff(ms,@timediff,getdate()) as 耗时 set nocount off
END GO

调用示例

GO

DECLARE    @return_value int,
@recordTotal int EXEC @return_value = [dbo].[P_GridViewPager]
@recordTotal = @recordTotal OUTPUT,
@viewName = N'Study_StudentStatistics',
@fieldName = N'termcourseid,loginname',
@keyName = N'id',
@pageSize = 200,
@pageNo = 1,
@orderString = N'id' SELECT @recordTotal as N'@recordTotal' SELECT 'Return Value' = @return_value GO