Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get records from the table by using "Select top(5) itemCode,ItemName,Price from Item"
Now I wan't to take next 5 records. How can I create query to that one.
After that I wan't to take the previous 5 records also.
Posted
Updated 5-Apr-11 17:37pm
v2

Hi,

Here is a stored procedure that will do it for you, just compile it on your server and run it using either 1 or 0 as a parameter.

You will see if you use 1 as a parameter it will return top 5, otherwise 0 will return the next 5

<br />
execute SP_GetTop5CP 1<br />
execute SP_GetTop5CP 0<br />
execute SP_GetTop5CP 1<br />



SQL
if (object_id('SP_GetTop5CP') is not null)
begin
    drop proc SP_GetTop5CP
end
go
/*
This stored procedure will return the top 5 if called with 1 parameter
and will return the 6-10 if called with 0 parameter
*/
create proc SP_GetTop5CP @First5 bit = 1
as
begin
    declare @i int
    select top(10) itemCode,ItemName,Price into #1 from Item
    alter table #1 add IDX int
    set @i = 0
    update #1 set IDX = @i, @i = @i + 1
    if (@First5 = 1)
    begin
        --you want to get the first 5
        delete from #1 where IDX > 5
    end
    else
    begin
        --you want to get the next 5
        delete from #1 where IDX <= 5
    end
    alter table #1 drop column IDX
    select * from #1
end
go
grant exec on SP_GetTop5CP to public
go



Hope this helps

Regards

Terence
 
Share this answer
 
Comments
arindamrudra 6-Apr-11 1:31am    
Excellent answer, but in case of 11th to 15th or 11th to 13th (if it varies).
SwitcherSoft 6-Apr-11 1:36am    
Thanks,

If that was the case i would pass record_from and record_to to the stored procedure. But perhaps there is a less expensive way of doing it? Let me check a bit.
Your database schema is going to have to support doing this. You can't do it for just any table. Read these[^].
 
Share this answer
 
Hi,
Here is a stored procedure that will do it for you in case of 11th to 15th or 11th to 13th (if it varies)

SQL
create proc SP_GetTopNCP
    @RecSize    INT,
    @PageNo     INT
as
begin
    select ROW_NUMBER() OVER(ORDER BY itemCode ASC) as [rowId],itemCode,ItemName,Price into #1 from Item
    select top(RecSize) * from #1 WHERE rowID> (@RecSize * (@PageNo-1))
end
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900