SQL存储过程分页(通用的拼接SQL语句思路实现)

时间:2022-09-04 19:23:21

多表通用的SQL存储过程分页

案例一:

USE [Community]
GO /****** Object: StoredProcedure [dbo].[Common_PageList] Script Date: 2016/3/8 13:44:58 ******/
SET ANSI_NULLS ON
GO SET QUOTED_IDENTIFIER ON
GO CREATE PROCEDURE [dbo].[Common_PageList]
(
@tab nvarchar(200),---表名
@strFld nvarchar(max), --字段字符串
@strWhere nvarchar(max), --where条件
@PageIndex int, --页码
@PageSize int, --每页容纳的记录数
@Sort nvarchar(255), --排序字段及规则,不用加order by
@Total int output --总数
)
AS
declare @strSql nvarchar(max)
set nocount on; set @strSql=' SELECT * FROM (SELECT ROW_NUMBER()
OVER(ORDER BY ' + @Sort + ') AS rownum, ' + @strFld + ' FROM ' + @tab + ' where 1=1 ' + @strWhere + ') AS Dwhere
WHERE rownum BETWEEN ' + CAST(((@PageIndex-1)*@PageSize + 1) as nvarchar(20)) + ' and ' + cast((@PageIndex*@PageSize) as nvarchar(20))
exec (@strSql)
--print @strSql set @strSql='SELECT @Total = COUNT(0) FROM ' + @tab + ' WHERE 1=1 ' + @strWhere
--print @strSql
EXECUTE sp_executesql @strSql,N'@Total INT OUTPUT',@Total OUTPUT set nocount off; GO

分页功能可以简化整合成统一的 SQL语句分页壳子 功能:

USE [Community]
GO /****** Object: StoredProcedure [dbo].[GetMySocialList] Script Date: 2016/3/17 15:20:18 ******/
SET ANSI_NULLS ON
GO SET QUOTED_IDENTIFIER ON
GO -- =============================================
-- Author: 熊学浩
-- Create date: 2016-03-17
-- Description: “我的圈子"列表
-- =============================================
CREATE PROCEDURE [dbo].[GetMySocialList]
-- Add the parameters for the stored procedure here
@MemberID int, --用户ID
@PageIndex int, --页码
@PageSize int, --每页容纳的记录数
@Total int output --总数
AS
declare @strSql nvarchar(max);
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON; --主查询
set @strSql='SELECT
S.CMSocialID,
S.SocialName,
S.SocialDescription,
S.SocialLogo,
S.SocialAuthority,
S.Integral,
S.SocialState,
S.IsAvailable,
SC.CheckState,
SC.Notes,
SM.CMSocialMemberID,
SM.MemberID,
SM.MemberName,
SM.MemberIntegral,
SM.EnterTime,
SM.MemberState,
SM.MemberRank,
SM.IsRecommend
FROM (SELECT * FROM CMSocialMember WHERE MemberID='+ CAST(@MemberID as nvarchar(20))+' AND IsDelete<>1 AND IsAvailable=1) AS SM
INNER JOIN CMSocial AS S ON S.CMSocialID=SM.CMSocialID
LEFT JOIN (
SELECT *
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY CMSocialID ORDER BY CreateTime DESC) AS group_index ,*
FROM CMSocialCheck WHERE IsDelete<>1
) AS SCsub WHERE SCsub.group_index=1
) AS SC ON SC.CMSocialID=SM.CMSocialID '; --WHERE S.IsAvailable = 1 print(@strSql); --拼接分页壳子
set @strSql='SELECT A.*
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY ASub.CMSocialID DESC) AS RowNumber,* FROM
('
+ @strSql +
' ) AS ASub
) AS A
WHERE RowNumber BETWEEN ' + CAST(((@PageIndex-1)*@PageSize + 1) as nvarchar(20)) + ' AND ' + CAST((@PageIndex*@PageSize) as nvarchar(20));
print(@strSql);
exec (@strSql); --获取总记录数
set @strSql='SELECT @Total = COUNT(1) FROM(
(SELECT CMSocialID FROM CMSocialMember WHERE MemberID=1 AND IsDelete<>1 AND IsAvailable=1) AS SM
INNER JOIN CMSocial AS S ON S.CMSocialID=SM.CMSocialID
)';
print(@strSql);
EXECUTE sp_executesql @strSql,N'@Total INT OUTPUT',@Total OUTPUT; SET NOCOUNT OFF;
END GO

也可以结合存储过程和实物:

USE [TestDB]
GO /****** Object: StoredProcedure [dbo].[GetPageDataList] Script Date: 11/16/2017 14:13:46 ******/
SET ANSI_NULLS ON
GO SET QUOTED_IDENTIFIER ON
GO -- =============================================
-- Author: <Author,,熊学浩>
-- Create date: <Create Date,,2017/11/16>
-- Description: <Description,,Sql存储过程分页>
-- =============================================
CREATE PROC [dbo].[GetPageDataList]
(
@TableName varchar(5000), --表名
@Fields varchar(5000) = '*', --字段名(全部字段为*)
@OrderField varchar(5000), --排序字段(必须!支持多字段)
@OrderType varchar(5000), --排序类型
@sqlWhere varchar(5000) = Null, --条件语句(不用加where)
@pageSize int, --每页多少条记录
@pageIndex int = 1 , --指定当前为第几页
@TotalPage int output, --返回总页数
@totalRecord int output --计算总记录数 --返回总记录数 )
AS
begin Begin Tran --开始事务 Declare @sql nvarchar(500);
if (@SqlWhere='' or @sqlWhere=NULL)
set @sql = 'select @totalRecord = count(*) from ' + @TableName
else
set @sql = 'select @totalRecord = count(*) from ' + @TableName + ' where ' + @sqlWhere
EXEC sp_executesql @sql,N'@totalRecord int OUTPUT',@totalRecord OUTPUT--计算总记录数 --计算总页数
select @TotalPage=CEILING((@totalRecord+0.0)/@PageSize) if (@SqlWhere='' or @sqlWhere=NULL)
set @sql = 'Select * FROM (select ROW_NUMBER() Over(order by ' + @OrderField +' ' + @Ordertype+' ) as rowId,' + @Fields + ' from ' + @TableName
else
set @sql = 'Select * FROM (select ROW_NUMBER() Over(order by ' + @OrderField +' ' + @Ordertype+' ) as rowId,' + @Fields + ' from ' + @TableName + ' where ' + @SqlWhere --处理页数超出范围情况
if @PageIndex<=0
Set @pageIndex = 1 if @pageIndex>@TotalPage
Set @pageIndex = @TotalPage --处理开始点和结束点
Declare @StartRecord int
Declare @EndRecord int set @StartRecord = (@pageIndex-1)*@PageSize + 1
set @EndRecord = @StartRecord + @pageSize - 1 --继续合成sql语句
set @Sql = @Sql + ') as ' + @TableName + ' where rowid between ' + Convert(varchar(50),@StartRecord) + ' and ' + Convert(varchar(50),@EndRecord)
--print @Sql Exec(@Sql)
---------------------------------------------------
If @@Error <> 0
Begin
RollBack Tran
Return -1
End
Else
Begin
Commit Tran
Return @totalRecord ---返回记录总数
End
end GO

案例二:

USE [Community]
GO /****** Object: StoredProcedure [dbo].[Common_PageListS] Script Date: 2016/3/8 13:46:25 ******/
SET ANSI_NULLS ON
GO SET QUOTED_IDENTIFIER ON
GO CREATE PROCEDURE [dbo].[Common_PageListS]
(
@Tables nvarchar(1000), --表名/视图名
@PrimaryKey nvarchar(100), --主键
@Sort nvarchar(200) = NULL, --排序字段(不带order by)
@pageindex int = 1, --当前页码
@PageSize int = 10, --每页记录数
@Fields nvarchar(1000) = N'*', --输出字段
@Filter nvarchar(1000) = NULL, --where过滤条件(不带where)
@Group nvarchar(1000) = NULL, --Group语句(不带Group By)
@TotalCount int OUTPUT --总记录数
)
AS DECLARE @SortTable nvarchar(100)
DECLARE @SortName nvarchar(100)
DECLARE @strSortColumn nvarchar(200)
DECLARE @operator char(2)
DECLARE @type nvarchar(100)
DECLARE @prec int --设定排序语句
IF @Sort IS NULL OR @Sort = ''
SET @Sort = @PrimaryKey
IF CHARINDEX('DESC',@Sort)>0
BEGIN
SET @strSortColumn = REPLACE(@Sort, 'DESC', '')
SET @operator = '<='
END
ELSE
BEGIN
SET @strSortColumn = REPLACE(@Sort, 'ASC', '')
SET @operator = '>='
END
IF CHARINDEX('.', @strSortColumn) > 0
BEGIN
SET @SortTable = SUBSTRING(@strSortColumn, 0, CHARINDEX('.',@strSortColumn))
SET @SortName = SUBSTRING(@strSortColumn, CHARINDEX('.',@strSortColumn) + 1, LEN(@strSortColumn))
END
ELSE
BEGIN
SET @SortTable = @Tables
SET @SortName = @strSortColumn
END --设置排序字段类型和精度
SELECT @type=t.name, @prec=c.prec FROM sysobjects o
JOIN syscolumns c on o.id=c.id
JOIN systypes t on c.xusertype=t.xusertype WHERE o.name = @SortTable AND c.name = @SortName IF CHARINDEX('char', @type) > 0
SET @type = @type + '(' + CAST(@prec AS varchar) + ')' DECLARE @strPageSize nvarchar(50)
DECLARE @strStartRow nvarchar(50)
DECLARE @strFilter nvarchar(1000)
DECLARE @strSimpleFilter nvarchar(1000)
DECLARE @strGroup nvarchar(1000) IF @pageindex <1
SET @pageindex = 1
SET @strPageSize = CAST(@PageSize AS nvarchar(50))
--设置开始分页记录数
SET @strStartRow = CAST(((@pageindex - 1)*@PageSize + 1) AS nvarchar(50))
--筛选以及分组语句
IF @Filter IS NOT NULL AND @Filter != ''
BEGIN
SET @strFilter = ' WHERE ' + @Filter + ' '
SET @strSimpleFilter = ' AND ' + @Filter + ' '
END
ELSE
BEGIN
SET @strSimpleFilter = ''
SET @strFilter = ''
END
IF @Group IS NOT NULL AND @Group != ''
SET @strGroup = ' GROUP BY '
--计算总记录数
DECLARE @TotalCountSql nvarchar(1000)
SET @TotalCountSql=N'SELECT @TotalCount=COUNT(*)' +N' FROM ' + @Tables+N' WITH(NOLOCK) ' + @strFilter
EXEC sp_executesql @TotalCountSql,N'@TotalCount int OUTPUT',@TotalCount OUTPUT
--执行查询语句
EXEC(
'
DECLARE @SortColumn ' + @type + '
SET ROWCOUNT ' + @strStartRow + '
SELECT @SortColumn=' + @strSortColumn + ' FROM ' + @Tables+N' WITH(NOLOCK) ' + @strFilter + ' ' + @strGroup + ' ORDER BY ' + @Sort + '
SET ROWCOUNT ' + @strPageSize + '
SELECT ' + @Fields + ' FROM ' + @Tables+N' WITH(NOLOCK) ' + ' WHERE ' + @strSortColumn + @operator + ' @SortColumn ' + @strSimpleFilter + ' ' + @strGroup + ' ORDER BY ' + @Sort + '
'
) GO

案例三:

SQL Server 2012以上版本支持以下存储过程排序:

 USE [Community]
GO /****** Object: StoredProcedure [dbo].[SP_CMSocial_QueryCMSocialShow] Script Date: 2016/10/26 15:21:28 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CMSocial_QueryCMSocialShow]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CMSocial_QueryCMSocialShow]
GO /****** Object: StoredProcedure [dbo].[SP_CMSocial_QueryCMSocialShow] Script Date: 2016/10/26 15:21:28 ******/
SET ANSI_NULLS ON
GO SET QUOTED_IDENTIFIER ON
GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CMSocial_QueryCMSocialShow]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[SP_CMSocial_QueryCMSocialShow] AS'
END
GO -- =============================================
-- Author: 熊学浩
-- Create date: 2016-10-26
-- Description: 圈子广场
-- =============================================
ALTER PROCEDURE [dbo].[SP_CMSocial_QueryCMSocialShow]
@CMSocialCategoryID bigint=NULL,
@IndustryID bigint=NULL,
@ProvinceID bigint=NULL,
@SearchWords nvarchar(200)=NULL, @SortMode varchar(20)='CreateTime,MemberNumber', /* @SortMode='CreateTime,MemberNumber' / 'CreateTime' / 'MemberNumber' */
@StartingRowNumber bigint=0,
@FetchRows int=12,
@NeedTotal bit=0 --是否需要获取总数
AS
BEGIN
if(@CMSocialCategoryID='' or @CMSocialCategoryID<1) set @CMSocialCategoryID=null;
if(@IndustryID='' or @IndustryID<1) set @IndustryID=null;
if(@ProvinceID='' or @ProvinceID<1) set @ProvinceID=null;
if(@SearchWords is not null and @SearchWords!='' and LEN(@SearchWords)>0) set @SearchWords = '%'+@SearchWords+'%';
else set @SearchWords=null; declare @Total bigint=0; -- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON; select * from(
SELECT
S.CMSocialID AS 'ID',
S.CMSocialID,
S.SocialName,
S.SocialDescription,
S.SocialLogo,
S.SocialAuthority,
S.Integral,
S.SocialState,
S.IsAvailable,
S.ModifyTime,
S.CreateTime,
COUNT(DISTINCT SM.CMSocialMemberID) AS 'MemberNumber'
FROM CMSocial AS S
LEFT JOIN (SELECT * FROM CMSocialMember WHERE CMSocialMember.IsDelete<>1 AND CMSocialMember.IsAvailable=1) AS SM ON S.CMSocialID = SM.CMSocialID
WHERE S.IsAvailable=1 AND S.SocialState=0
AND (S.CMSocialID IN(SELECT DISTINCT CMSocialID FROM CMSocialCategoryRelation WHERE CMSocialCategoryID IN(@CMSocialCategoryID)) OR @CMSocialCategoryID IS NULL)
AND (S.CMSocialID IN(SELECT DISTINCT CMSocialID FROM CMIndustryRelation WHERE IndustryID IN(@IndustryID)) OR @IndustryID IS NULL)
AND (S.CMSocialID IN(SELECT DISTINCT CMSocialID FROM CMAreaRelation WHERE ProvinceID IN(@ProvinceID)) OR @ProvinceID IS NULL)
AND ((S.SocialName LIKE @SearchWords OR S.SocialDescription LIKE @SearchWords) OR @SearchWords IS NULL)
GROUP BY
S.CMSocialID,
S.SocialName,
S.SocialDescription,
S.SocialLogo,
S.SocialAuthority,
S.Integral,
S.SocialState,
S.IsAvailable,
S.ModifyTime,
S.CreateTime
) as T
--ORDER BY T.CreateTime DESC,T.MemberNumber DESC
--ORDER BY MemberNumber DESC
ORDER BY /* @SortMode='CreateTime,MemberNumber' / 'CreateTime' / 'MemberNumber' 多字段,多优先级排序 */
CASE WHEN (CHARINDEX('CreateTime',@SortMode)=1) THEN (T.CreateTime) END DESC,
CASE WHEN (CHARINDEX('MemberNumber',@SortMode)=1) THEN T.MemberNumber END DESC,
CASE WHEN (CHARINDEX('CreateTime',@SortMode)>1) THEN (T.CreateTime) END DESC,
CASE WHEN (CHARINDEX('MemberNumber',@SortMode)>1) THEN T.MemberNumber END DESC OFFSET @StartingRowNumber ROWS
FETCH NEXT @FetchRows ROWS ONLY; if(@NeedTotal=1)
begin
SELECT @Total=COUNT(*)
FROM CMSocial AS S
WHERE S.IsAvailable=1 AND S.SocialState=0
AND (S.CMSocialID IN(SELECT DISTINCT CMSocialID FROM CMSocialCategoryRelation WHERE CMSocialCategoryID IN(@CMSocialCategoryID)) OR @CMSocialCategoryID IS NULL)
AND (S.CMSocialID IN(SELECT DISTINCT CMSocialID FROM CMIndustryRelation WHERE IndustryID IN(@IndustryID)) OR @IndustryID IS NULL)
AND (S.CMSocialID IN(SELECT DISTINCT CMSocialID FROM CMAreaRelation WHERE ProvinceID IN(@ProvinceID)) OR @ProvinceID IS NULL)
AND ((S.SocialName LIKE @SearchWords OR S.SocialDescription LIKE @SearchWords) OR @SearchWords IS NULL)
end
else
begin
set @Total=0;
end return @Total; SET NOCOUNT OFF;
END GO

高效的SQLSERVER分页查询的几种示例分析

http://www.cnblogs.com/xiongzaiqiren/p/sql-paging.html

SQL存储过程分页(通用的拼接SQL语句思路实现)的更多相关文章

  1. 通用SQL存储过程分页以及asp&period;net后台调用

    创建表格并添加300万数据 use Stored CREATE TABLE UserInfo( --创建表 id ,) PRIMARY KEY not null,--添加主键和标识列 UserName ...

  2. SQL 存储过程 分页 分类: SQL Server 2014-05-16 15&colon;11 449人阅读 评论&lpar;0&rpar; 收藏

    set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go -- ============================================= -- Au ...

  3. sql 存储过程 分页

    ALTER PROCEDURE [dbo].[BrokerToLenderDataShow2]@Where VARCHAR(200), --查询条件 不含'where'字符,如id>10 and ...

  4. SQL 存储过程 分页查询

    ALTER PROCEDURE [dbo].[gzProc_TablePage] @tablename varchar(MAX),--表名 @selcolumn varchar(MAX),--查询字段 ...

  5. Sql存储过程分页--临时表存储

    set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go -- ============================================= -- Au ...

  6. SQL存储过程分页

    CREATE PROC ZDY_FY(@Pages INT, @pageRow INT) --@Pages第几页 @pageRow每页显示几行 AS BEGIN DECLARE @starNum IN ...

  7. SQL 存储过程分页

    CREATE PROC p_Team_GetTemaList @pageindex INT , @pagesize INT , @keywords VARCHAR(200) , --模糊查询 名称 标 ...

  8. SQL行转列&plus;动态拼接SQL

    数据源       Name AreaName qty Specific 叶玲 1 60 1 叶玲 2 1 1 叶玲 6 1 0 叶玲 7 5 0 叶玲 8 1 1 显示效果: Name 1 2 8 ...

  9. SQLServer 存储过程中不拼接SQL字符串实现多条件查询

    以前拼接的写法 set @sql=' select * from table where 1=1 ' if (@addDate is not null) set @sql = @sql+' and a ...

随机推荐

  1. AMD and CMD are dead之KMDjs内核之分号

    在老版本的kmdjs中,强制了分号的要求.但是总感觉不爽,因为在开发Ket - Kmdjs Extension Tools的时候,总需要导入一些开源的库,然后痛苦就来了,总是报错,一查,就是缺少分号! ...

  2. Qt 获取cmd运行结果

    http://www.cnblogs.com/gisbeginner/archive/2012/12/08/2809063.html BOOL ExecDosCmd(){ #define EXECDO ...

  3. July 7th&comma; Week 28th Thursday&comma; 2016

    The 79th Anniversary of Anti-Japan War Difficulties vanish when faced bodly. 勇敢面对困难,困难自会退让. The best ...

  4. SQL中PERSISTED关键字

    PERSISTED 指定 SQL Server 数据库引擎将在表中物理存储计算值,而且,当计算列依赖的任何其他列发生更新时对这些计算值进行更新.将计算列标记为 PERSISTED,可允许您对具有确定性 ...

  5. 【李婶小教程】(SE&lowbar;lab3)

    额,今天说一下这个SE_lab3那几个东西都是怎么装的. 啊--其实技术含量貌似不是很高的. 1.先说最简单的一个叫做:Findbugs 点这个Eclipse Marketplace,这是一个神奇的东 ...

  6. Git 系列(四):在 Git 中进行版本回退

    在这篇文章中,你将学到如何查看项目中的历史版本,如何进行版本回退,以及如何创建 Git 分支以便你可以大胆尝试而不会出现问题. 在你的 Git 项目的历史中,你的位置就像是摇滚专辑中的一个片段,由一个 ...

  7. Git submodule - 子模块【转】

    子模块 有种情况我们经常会遇到:某个工作中的项目需要包含并使用另一个项目. 也许是第三方库,或者你独立开发的,用于多个父项目的库. 现在问题来了:你想要把它们当做两个独立的项目,同时又想在一个项目中使 ...

  8. SSH下authorized&lowbar;keys&comma; id&lowbar;rsa&comma; id&lowbar;rsa&period;pub&comma; known&lowbar;hosts作用

    一.known_hsots ssh会把你每个你访问过计算机的公钥(public key)都记录在~/.ssh/known_hosts.当下次访问相同计算机时,OpenSSH会核对公钥.如果公钥不同,O ...

  9. 那些年用过的Redis集群架构

    今天我们来谈谈Redis集群这个话题,需要说明的是本文 适合人群:不知道自己生产redis集群架构,以及对Redis集群不了解的人 不适合群: 对自己生产Redis集群架构非常了解的人 本文预计分两个 ...

  10. 状态机学习(三)解析JSON1

    来自 从零开始的 JSON 库教程 从零开始教授如何写一个符合标准的 C 语言 JSON 库 作者 Milo Yip https://zhuanlan.zhihu.com/json-tutorial ...