Ardalan Shahgholi
Ardalan Shahgholi

Reputation: 12565

Get N last rows from table with one stored procedure

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 :

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  

Upvotes: 1

Views: 1543

Answers (2)

Ardalan Shahgholi
Ardalan Shahgholi

Reputation: 12565

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; 

Upvotes: 0

user2151306
user2151306

Reputation: 21

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;

Upvotes: 2

Related Questions