Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19269829
  • 博文数量: 7460
  • 博客积分: 10434
  • 博客等级: 上将
  • 技术积分: 78178
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-02 22:54
文章分类

全部博文(7460)

文章存档

2011年(1)

2009年(669)

2008年(6790)

分类: Oracle

2008-03-21 14:42:29

sql 存储过程分页

CREATE PROC myx_prPageRecordset
@queryStr nvarchar(1000),
@keyField nvarchar (200),
@pageSize int,
@pageNumber int
AS
BEGIN
DECLARE @sqlText AS nvarchar(4000)
DECLARE @sqlTable AS nvarchar(4000)
SET @sqlTable = 'SELECT TOP ' + CAST((@pageNumber + 1) * @pageSize AS varchar(30)) + ' ' + @queryStr
SET @sqlText =
'SELECT TOP ' + CAST(@pageSize AS varchar(30)) + ' * ' +
'FROM (' + @sqlTable + ') AS tableA ' +
'WHERE ' + @keyField + ' NOT IN(SELECT TOP ' +
CAST(@pageNumber * @pageSize AS varchar(30)) + ' ' + @keyField +
' FROM (' + @sqlTable + ') AS tableB)'
EXEC (@sqlText)
END

GO

核心代码
Dim strsql As String
myComm = New SqlClient.SqlCommand("myx_prPageRecordset", myConn)
myComm.CommandType = CommandType.StoredProcedure
myComm.Parameters.Add(New SqlClient.SqlParameter("@queryStr", SqlDbType.NVarChar, 1000))
myComm.Parameters("@queryStr").Value = " * from tbpage order by id DESC"
myComm.Parameters.Add(New SqlClient.SqlParameter("@keyField", SqlDbType.NVarChar, 200))
myComm.Parameters("@keyField").Value = "[id]"
myComm.Parameters.Add(New SqlClient.SqlParameter("@pageSize", SqlDbType.NVarChar, 1000))
myComm.Parameters("@pageSize").Value = PageSize
myComm.Parameters.Add(New SqlClient.SqlParameter("@pageNumber", SqlDbType.NVarChar, 1000))
myComm.Parameters("@pageNumber").Value = myPage - 1

呵呵,执行几W条的代码只需150毫秒左右

建立一个test(id,name,fid)
向test添充几十条数据,使id=1,2,3,4.........(即递增的integer),其他任意
在T-sql Debugger给改存储过程分别传递如下参数:
@queryStr= * from test
@keyField=[ID]
@pageSize=3
@pageNumber=1
问题出来了,看输出结果(注意id):
id name fid
4 kwklover 2
5 kwklover 2
6 kwklover 2
根据传入参数,我们的预期应该是:
id name fid
1 kwklover 2
2 kwklover 2
3 kwklover 2

下面是我参照小春的存储分页写的分页存储过程,可以解决上面的问题:
CREATE Procedure prGetRecordByPage
(
@PageSize int, --每页的记录条数
@PageNumber int, --当前页面
@QuerySql varchar(1000),--部分查询字符串,如* From Test order by id desc
@KeyField varchar(500)
)
AS
Begin

Declare @SqlTable AS varchar(1000)
Declare @SqlText AS Varchar(1000)

Set @SqlTable='Select Top '+CAST(@PageNumber*@PageSize AS varchar(30))+'
Set @SqlText='Select Top '+Cast(@PageSize AS varchar(30))+' * From '
+'() As TembTbA '
+'Where Not In (Select Top '+CAST((@PageNumber-1)*@PageSize AS varchar(30))+' From '
+'() AS TempTbB)'
Exec(@SqlText)

End
GO

阅读(320) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~