SqlServer內部的分頁功能

來源:互聯網
上載者:User
方式一:
--利用SQL未公開的預存程序實現分頁        if exists (select * from dbo.sysobjects          where id = object_id(N'[dbo].[p_splitpage]')          and OBJECTPROPERTY(id, N'IsProcedure') = 1)        drop procedure [dbo].[p_splitpage]        GO             create procedure p_splitpage            @sql nvarchar(4000), --要執行的sql語句        @currentpage int=2, --要顯示的頁碼        @pagesize int=10, --每頁的大小        @recordcount int=0 out, --記錄數        @pagecount int=0 out --總頁數        as        set nocount on        declare @p1 int             exec sp_cursoropen @p1 output,@sql,@scrollopt=1,@ccopt=1,@rowcount=@pagecount output             select @recordcount=@pagecount,@pagecount=ceiling(1.0*@pagecount/@pagesize)            ,@currentpage=(@currentpage-1)*@pagesize+1            select @recordcount recordcount ,@pagecount     pagecount,@currentpage     currentpage        exec sp_cursorfetch @p1,16,@currentpage,@pagesize            exec sp_cursorclose @p1        go

方式二:

CREATE PROC spGetPages2 @iRowCount INT,@iPageNo INTASSELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY ProductID ASC) RowNum,* FROM Production.Product ) OrderDataWHERE RowNum BETWEEN @iRowCount*(@iPageNo-1)+1 AND @iRowCount*@iPageNoORDER BY ProductID ASCGOEXEC spGetPages2 10,20
----------------------------------方式三:1)只需要提供Sql語句和每頁的記錄數,頁數就可以了2)速度超快喲,100W記錄1~3秒就分出來了3)對於預存程序特別好用

--//調用的方式

exec up_zbh_DivPageBySql 'select * from 表',10,3
預存程序
exec up_zbh_DivPageBySql 'exec 預存程序',10,1

--//我把它封裝成一個預存程序,調用的時候方便的很哈!!
create procedure up_zbh_DivPageBySql
 @strSql varchar(8000),
 @nPageSize int,
 @nPageCount int
as
    SET NOCOUNT ON 
    DECLARE @P1 INT,
    @nRowCount INT

    --//注意:@scrollopt = 1 會取得Select的時候的總行數
    EXEC sp_cursoropen @P1 OUTPUT, @strSql, @scrollopt = 2, @ccopt = 335873, @rowcount = @nRowCount OUTPUT

    IF (@P1 != 0)
    BEGIN
--SELECT @nRowCount AS nRecordCount, ceiling(1.0 * @nRowCount / @nPageSize) AS nPageCount, @nPageCount AS nPage
SET @nPageCount = (@nPageCount - 1) * @nPageSize + 1 
EXEC sp_cursorfetch @P1, 32, @nPageCount, @nPageSize  
EXEC sp_cursorclose @P1
    END

GO

--//調用的方式

exec up_zbh_DivPageBySql 'select * from ptype',10,4
預存程序
exec up_zbh_DivPageBySql 'exec 預存程序',10,1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.