自已写的几个分页的存储过程
?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
/*分頁(yè)查找數(shù)據(jù)*/
ALTER PROCEDURE [dbo].[GetRecordSet]
@strSql varchar(8000),--查詢sql,如select * from [user]
@PageIndex int,--查詢當(dāng)頁(yè)號(hào)
@PageSize int--每頁(yè)顯示記錄
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 --得到總記錄數(shù)
select @PageCount=ceiling(1.0*@rowCount/@pagesize) --得到總頁(yè)數(shù)
,@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),??? --字段列表(不帶類型),用于分頁(yè)部分讀取@t表變量的字段,也可使用*代替,但性能會(huì)下降,如:PhotoID ,UserID ,PhotoTitle?
@selectSrting nvarchar(2000), --向@t表變量中讀取記錄的Select語(yǔ)句?
@resultOrderBy nvarchar(200), --對(duì)分頁(yè)結(jié)果進(jìn)行排序的字段,如:升序'PhotoID ASC'、降序'PhotoID DESC',注意:如果是降序的話要在selectSrting和此處都加DESC?
@pageSize INT,??????????????? --頁(yè)尺寸,0表示返回所有行?
@currentPage INT,???????????? --當(dāng)前頁(yè),首頁(yè)為1?
@RecordCount INT OUTPUT?????? --非0值則返回記錄總數(shù)?
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
總結(jié)
以上是生活随笔為你收集整理的自已写的几个分页的存储过程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 飞鸽传书 宣传单和电话说辞
- 下一篇: 趣味故事嘛的facebook中文网