Get N last rows from table with one stored procedure

。_饼干妹妹 提交于 2019-12-11 07:57:07

问题


I want get N last rows from table with one stored procedure.

My stored procedure has some parameters like @PageNumber and @RowCount and etc.

I have 2 problems :

  • I need to count the rows and results in my user interface because I want to limit my user when he is in last page and press next page.

  • I want my user can press last page when he is in other page.

Tip: I don't want to execute my stored procedure twice to get the results and row count because it creates dynamic and need long time for execution.

For more description I most say that my sp is like :

Create Procedure TestSelectBill  
(  
    @PageNumber int = 1 ,  
    @RowCount int = 5  
)  
As  
Begin  
    Select   
        *  
    From billing.BillMaster As BM  
    Where  
    ( Bm.SubscribeId = '12345674' )  
    Order by SubscribeId  
    OFFSET @PageNumber * @RowCount ROWS  
    FETCH NEXT @RowCount ROWS ONLY;  
End  

回答1:


You can use Row_Number() in your query and order SubscribeId descending and row[0]["RowNumber"] is total count like this:

Select
        *  ,
ROW_NUMBER() OVER ( ORDER BY SubscribeId DESC) as RowNumber
    From billing.BillMaster As BM  
    Where  
    ( Bm.SubscribeId = '12345674' )  
    Order by SubscribeId  
    OFFSET @PageNumber * @RowCount ROWS  
    FETCH NEXT @RowCount ROWS ONLY;



回答2:


That is my solution:

Select
  COUNT() OVER ( ORDER BY (SELECT NULL)) as RowNumber,
    * 
From billing.BillMaster As BM  
Where  
( Bm.SubscribeId = '12345674' )  
Order by SubscribeId  
OFFSET (@PageNumber - 1) * @RowCount ROWS  
FETCH NEXT @RowCount ROWS ONLY; 


来源:https://stackoverflow.com/questions/15308706/get-n-last-rows-from-table-with-one-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!