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))+' '+@QuerySql
Set @SqlText='Select Top '+Cast(@PageSize AS varchar(30))+' * From '
+'('+@SqlTable+') As TembTbA '
+'Where '+@KeyField+' Not In (Select Top '+CAST((@PageNumber-1)*@PageSize AS varchar(30))+' '+@KeyField+' From '
+'('+@SqlTable+') AS TempTbB)'
Exec(@SqlText)
End
GO