本文主要談談Java調用SQL Server分頁存儲的過程,其返回是多個結果集,只要呈現形式是代碼,文字不多,簡單易懂。
SQL存儲過程:
- USE [Db_8za8za_2]
- GO
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- -- =============================================
- -- Description: <Description,,通用分頁存儲過程>
- -- =============================================
- ALTER PROCEDURE [dbo].[paging ]
- -- Add the parameters for the stored procedure here
- --傳入參數
- @SqlStr nvarchar(4000), --查詢字符串
- @CurrentPage int, --第N頁(當前頁數)
- @PageSize int --每頁行數
- AS
- BEGIN
- -- SET NOCOUNT ON added to prevent extra result sets from
- -- interfering with SELECT statements.
- SET NOCOUNT ON;
- --定義變量
- DECLARE @CursorId int --CursorId是游標的id
- DECLARE @Rowcount int --總記錄(行)數
- DECLARE @pageCount int --總頁數
- -- Insert statements for procedure here
- EXEC sp_cursoropen @CursorId output,@SqlStr,
- @Scrollopt=1,@Ccopt=1,@Rowcount=@Rowcount OUTPUT
- SET @pageCount=CEILING(1.0*@Rowcount/@PageSize)--設置總頁數
- SELECT @pageCount
- AS 總頁數,@Rowcount AS 總行數,@CurrentPage AS 當前頁 --提示頁數
- IF(@CurrentPage>@pageCount)--如果傳入的當前頁碼大入總頁碼數則把當前頁數設為最後一頁
- BEGIN
- SET @CurrentPage = @pageCount--設置當前頁碼數
- END
- IF(@CurrentPage<=0)--如果傳入的當前頁碼大入總頁碼數則把當前頁數設為第一頁
- BEGIN
- SET @CurrentPage = 1--設置當前頁碼數
- END
- SET @CurrentPage=(@CurrentPage-1)*@PageSize+1 --設置當前頁碼數
- EXEC sp_cursorfetch @CursorId,16,@CurrentPage,@PageSize
- EXEC sp_cursorclose @CursorId --關閉游標
- SET NOCOUNT OFF
- END