标签:
CREATE PROCEDURE [dbo].[sp_TBTest_Query] ( @PageSize INT, --每页多少条记录 @PageIndex INT = 1, --指定当前为第几页 @PageCount INT OUTPUT, --返回总页数 @RecordCount INT OUTPUT, --记录总和 @OrderField VARCHAR(5000), --排序字段(多字段,不含Order By) @strWhere VARCHAR(5000), --条件语句(不用加where) @SumColumnNames NVARCHAR(200), --汇总字段 @SumResult NVARCHAR(200) OUTPUT --返回汇总结果 ) AS BEGIN DECLARE @SQL NVARCHAR(MAX) = ‘‘; --条件处理 IF ISNULL(@strWhere, ‘‘) =‘‘ BEGIN SET @strWhere=‘1=1 ‘ end --计算总记录数 SET @SQL = N‘SELECT @A = count(*) FROM TBTest where ‘+ @strWhere EXEC sp_executesql @SQL, N‘@A int OUTPUT‘, @RecordCount OUTPUT; --计算总页数 SELECT @PageCount = CEILING(( @RecordCount + 0.0 ) / @PageSize); --处理页数超出范围情况 IF @PageIndex <= 0 SET @PageIndex = 1; IF @PageIndex > @PageCount SET @PageIndex = @PageCount; --处理开始点和结束点 DECLARE @StartRecord INT; DECLARE @EndRecord INT; SET @StartRecord = ( @PageIndex - 1 ) * @PageSize + 1; SET @EndRecord = @StartRecord + @PageSize - 1; --计算汇总 IF ISNULL(@SumColumnNames, ‘‘) <> ‘‘ BEGIN SET @SQL = N‘SELECT @A = (CAST(ISNULL(SUM(‘ + REPLACE(@SumColumnNames, ‘,‘,‘), 0) AS NVARCHAR(30)) + ‘‘,‘‘ + CAST(ISNULL(SUM(‘) + ‘), 0) AS NVARCHAR(30))) FROM TBTest where ‘+@strWhere +‘ ‘ EXEC sp_executesql @SQL, N‘@A NVARCHAR(200) OUTPUT‘, @SumResult OUTPUT; END --返回结果 SET @sql=N‘ SELECT * FROM ( SELECT * ,ROW_NUMBER() OVER(ORDER BY id DESC) AS RowID FROM TBTest where ‘+@strWhere +N‘) t WHERE RowID BETWEEN ‘+CONVERT(NVARCHAR(10),@StartRecord)+N‘ AND ‘+CONVERT(NVARCHAR(10),@EndRecord) EXEC sp_executesql @SQL END
DECLARE @PageSize INT=10, --每页多少条记录 @PageIndex INT = 2, --指定当前为第几页 @PageCount INT , --返回总页数 @RecordCount INT , --记录总和 @OrderField VARCHAR(5000)=‘ID‘, --排序字段(多字段,不含Order By) @strWhere VARCHAR(5000)=‘‘, --条件语句(不用加where) @SumColumnNames NVARCHAR(200)=‘Age‘, --汇总字段 @SumResult NVARCHAR(200) --返回汇总结果 EXEC sp_TBTest_Query @PageSize,@PageIndex,@PageCount OUTPUT,@RecordCount OUTPUT,@OrderField,@strWhere,@SumColumnNames,@SumResult OUTPUT SELECT @PageCount AS ‘PageCount‘,@RecordCount AS ‘RecordCount‘,@SumResult AS ‘SUM‘
我在项目中遇到一个问题,就是元数据由分组,然后再连接,为了加快查询效率,我不得不剔除传入Where条件字符串中的一个条件,大概写法如下:
DECLARE @strWhere NVARCHAR(max)=‘ID=1 and Age=2 and address=‘‘销售部‘‘‘
DECLARE @str1 NVARCHAR(max)=‘‘
DECLARE @str2 NVARCHAR(max)=‘‘
IF ISNULL(@strWhere, ‘‘)<>‘‘
BEGIN
IF( CHARINDEX(‘Age‘,@strWhere)>0 )
BEGIN
SET @str1 =SUBSTRING(@strWhere,CHARINDEX(‘Age‘,@strWhere),LEN(@strWhere))
if CHARINDEX(‘and‘,@str1)>0
begin
SET @str2 =SUBSTRING(@str1,CHARINDEX(‘and‘,@str1),LEN(@str1))
end
SET @strWhere=SUBSTRING(@strWhere,0,CHARINDEX(‘Age‘,@strWhere))+N‘ 1=1 ‘+@str2
end
END
标签:
原文地址:http://www.cnblogs.com/stjwy/p/5971835.html