您的位置:首页 > 数据库 > SQL

自已写的几个分页的存储过程

2011-12-23 23:13 471 查看
 USE [master]

GO

/****** Object:  StoredProcedure [dbo].[GetRecordSet]    Script Date: 07/03/2011 23:55:34 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

/*分页查找数据*/

ALTER PROCEDURE [dbo].[GetRecordSet]

@strSql varchar(8000),--查询sql,如select * from [user]

@PageIndex int,--查询当页号

@PageSize int--每页显示记录

AS

set nocount on

declare @p1 int

declare @currentPage int

set @currentPage = 0

declare @RowCount int

set @RowCount = 0

declare @PageCount int

set @PageCount = 0

exec sp_cursoropen @p1 output,@strSql,@scrollopt=1,@ccopt=1,@rowcount=@rowCount output --得到总记录数

select @PageCount=ceiling(1.0*@rowCount/@pagesize) --得到总页数

,@currentPage=(@PageIndex-1)*@PageSize+1

select @RowCount,@PageCount

exec sp_cursorfetch @p1,16,@currentPage,@PageSize

exec sp_cursorclose @p1

set nocount off

 

 

 

Create PROCEDURE [dbo].[GetRecordWithPage] 

@fieldsType nvarchar(1000),   --字段列表(带类型),用于@t表变量的字段声明,如:PhotoID int,UserID int,PhotoTitle nvarchar(50) 

@fieldsList nvarchar(500),    --字段列表(不带类型),用于分页部分读取@t表变量的字段,也可使用*代替,但性能会下降,如:PhotoID ,UserID ,PhotoTitle 

@selectSrting nvarchar(2000), --向@t表变量中读取记录的Select语句 

@resultOrderBy nvarchar(200), --对分页结果进行排序的字段,如:升序'PhotoID ASC'、降序'PhotoID DESC',注意:如果是降序的话要在selectSrting和此处都加DESC 

@pageSize INT,                --页尺寸,0表示返回所有行 

@currentPage INT,             --当前页,首页为1 

@RecordCount INT OUTPUT       --非0值则返回记录总数 

AS 

BEGIN 

    DECLARE @strSql varchar(4000) 

    declare @sql nvarchar(1000) 

    SET @strSql = 'DECLARE @t TABLE(' +@fieldsType+ ');' 

    SET @strSql = @strSql + 'INSERT INTO @t '+@selectSrting+ ';' 

    set @sql = @strSql + 'select @aa=count(*) from @t;'  

    exec sp_executesql @sql,N'@aa int output',@RecordCount OUTPUT; 

    IF @pageSize=0 

        SET @strSql=@strSql+'SELECT '+@fieldsList+' FROM @t;' 

    ELSE 

        IF @currentPage=1 

            SET @strSql=@strSql+'select TOP('+STR(@pageSize)+')'+@fieldsList+' FROM @t;' 

        ELSE 

            BEGIN 

                SET @strSql =@strSql+'SELECT TOP('+Str(@pageSize)+')'+ @fieldsList+'FROM (SELECT TOP('+Str(@pageSize * @currentPage)+')'+@fieldsList+' , ROW_NUMBER() OVER (ORDER BY
'+@resultOrderBy+')' 

                SET @strSql =@strSql+' AS RowNumber FROM @t' 

                SET @strSql =@strSql+') AS r WHERE r.RowNumber >' + Str(@pageSize * (@currentPage - 1))+';' 

            END 

    EXEC(@strSql) 

END
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息