SQL查询通用存储过程(可分页)

以前参考过网上朋友(是谁忘了,知道的说一声)写的,但感觉有点不适合我的要求。修改大部分后如下所示。GetRecordPageTotal为分页时取得页总数。当然可以写在GetRecordByPage里,但个人认为那样的话,在只取页总数的情况下也要使用GetRecordByPage,查询效率不太好,就分开写


--///
if exists (select * from  sysobjects where  id = object_id('GetRecordPageTotal')and type = 'P')
   drop procedure GetRecordPageTotal
go
if exists (select * from  sysobjects where  id = object_id('PgetRecordByPage')and type = 'P')
   drop procedure PgetRecordByPage
go


--///
create procedure GetRecordPageTotal
    @tblName      varchar(100),                         -- 表名  
  --  @PageSize     int,                            -- 页大小
    @strWhere     varchar(1000) = ''                    -- 查询条件 (注意: 不要加 where)
as

begin
 declare @strSqlTemp varchar(2000)                -- 临时变量 
  
 
 if @strWhere=''
  set @strSqlTemp='select count(*) from ['+@tblName+']'
 else set @strSqlTemp='select count(*) from ['+@tblName+'] where '+@strWhere
 
 exec (@strSqlTemp)
end

GO

--
create procedure GetRecordByPage
    @tblName      varchar(100),       -- 表名
    @fldCow   varchar(100)='*',   -- 要查询的列
    @fldName      varchar(255),       -- 排序列
    @PageSize     int = 10,           -- 页尺寸
    @PageIndex    int = 1,            -- 页码
    @OrderType    bit = 1,            -- 设置排序类型, 1则降序
    @strWhere     varchar(2000) = ''  -- 查询条件 (注意: 不要加 where)
AS

declare @strSQL   varchar(3000)       -- 主语句
declare @strTmp   varchar(1000)       -- 临时变量
declare @strOrder varchar(500)        -- 排序类型

if @OrderType != 0
begin
    set @strTmp = '<(select min'
    set @strOrder = ' order by [' + @fldName + '] desc'
end
else
begin
    set @strTmp = '>(select max'
    set @strOrder = ' order by [' + @fldName + '] asc'
end

set @strSQL = 'select top ' + str(@PageSize) + ' '+@fldCow+' from ['
    + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
    + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
    + @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
    + @strOrder

if @strWhere != ''
    set @strSQL = 'select top ' + str(@PageSize) + ' '+@fldCow+ ' from ['
        + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
        + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
        + @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '
        + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder

if @PageIndex = 1
begin
    set @strTmp = ''
    if @strWhere != ''
        set @strTmp = ' where (' + @strWhere + ') '

    set @strSQL = 'select top ' + str(@PageSize) + ' '+@fldCow+ ' from ['
        + @tblName + ']' + @strTmp + ' ' + @strOrder
end

exec (@strSQL)
GO
注:不想分页的话,把PageSize 值设到int最大值就行了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值