在Sql Server中數據分頁

方法一:

    DECLARE @rowsPerPage int, 
    @pageNum int, 
    @startRow int, 
    @endRow int
    SET @rowsPerPage = 10 
    SET @pageNum = 3 
    SET @startRow = ((@pageNum- 1) * @rowsPerPage)+1 
    SET @endRow = @startRow + @rowsPerPage -1 
    SELECT * FROM ( 
    SELECT row_number() OVER (ORDER BY id) as resultNum, 
    id FROM myTable 
    ) as numberResults 
    WHERE resultNum BETWEEN @startRow AND @endRow

方法二(推薦):

    SET @rowsPerPage = 10 
    SET @pageNum = 3 
    With SQLPaging 
    As
    ( 
    Select Top(@rowsPerPage * @pageNum) ROW_NUMBER() OVER (ORDER BY id) as resultNum, id 
    FROM myTable 
    ) 
    select * from SQLPaging where resultNum > ((@pageNum - 1) * @rowsPerPage) 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章