欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

row number分頁存儲過程

程序员文章站 2022-03-02 14:58:01
...
USE [GoodsSystem]
GO
/****** 对象: StoredProcedure [dbo].[proc_table_paging] 脚本日期: 08/30/2010 16:03:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
使用 ROW_NUMBER() OVER 分页的例子

WITH tb_temp AS
(SELECT *,ROW_NUMBER() OVER (ORDER BY productid asc) as RowNumber from goods )

SELECT * FROM tb_temp WHERE RowNumber between 50 and 60;
*/
--exec [dbo].[proc_table_paging] 'goods','gid','','price',10,10000,9,'',1
--drop proc [dbo].[proc_table_paging]
-----------------------------------------------
-- 使用 ROW_NUMBER() OVER 分页的存储过程
-----------------------------------------------
CREATE PROCEDURE [dbo].[proc_table_paging]
@tblName varchar(255), -- 表名
@keyFields varchar(255), -- 主键列名
@strGetFields varchar(1000) = '*', -- 需要返回的列
@fldName varchar(255) = @keyFields, -- 排序的字段名
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@OrderType bit = 0, -- 设置排序类型, 非0值则降序
@strWhere varchar(1500) = '', -- 查询条件(注意: 不要加where)
@doCount bit = 0 -- 统计并返回记录总数, 非0值则返回

AS
declare @strSQL varchar(5000) -- 主语句
declare @strOrder varchar(400) -- 排序类型
declare @begin varchar(20) -- 起始行数
declare @end varchar(20) -- 结束行数

-- 默认返回所有列
if rtrim(ltrim(@strGetFields))=''
set @strGetFields='*'
-- 默认排序字段为主键列
if rtrim(ltrim(@fldName))=''
set @[email protected]
-- 默认每页大小为10行记录
if @PageSize<1
set @PageSize=10
-- 默认查询第一页
if @PageIndex<1
set @PageIndex=1
-- 默认没有where子句
if rtrim(ltrim(@strWhere))=''
set @strWhere=''
-- 默认为0时升序排列,否则降序排列
if @OrderType=0
set @strOrder = 'asc'
else
set @strOrder = 'desc'
-- 默认为0时不进行记录数的统计,否则统计并返回共有几条记录符合查询条件
if @doCount != 0
begin
if @strWhere !=''
set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere
else
set @strSQL = 'select count(*) as Total from [' + @tblName + ']'
exec (@strSQL)
end


-- 计算起始行数和终止行数
set @begin = cast( @PageSize*(@PageIndex-1)+1 as varchar(20) )
set @end = cast( @PageSize*@PageIndex as varchar(20) )

-- 构造临时表
if @strWhere!=''
begin
set @strSQL = 'WITH tb_temp AS (SELECT '[email protected]+' ,ROW_NUMBER() OVER (ORDER BY '[email protected]+' '[email protected]+' )as RowNumber from '[email protected]+' where '[email protected]+') '
end
else
begin
set @strSQL = 'WITH tb_temp AS (SELECT '[email protected]+' ,ROW_NUMBER() OVER (ORDER BY '[email protected]+' '[email protected]+' )as RowNumber from '[email protected]+') '
end

-- 从临时表中查询出结果
set @strSQL = @strSQL + ' SELECT '[email protected]+' FROM tb_temp WHERE RowNumber between '[email protected]+' and '[email protected]

print @strSQL
exec (@strSQL)


相关标签: Go SQL 脚本