Sunday, May 14, 2017

Sql Server: Get records from/after specific record/id

In this article I am going to explain how to select records after a specific record/Id in sql server.


Description:
I want to get records from a specific record or id. I have created a table Tb_Country and insert some dummy records.


Implementation:

Sql query to get records from specific Id:
I want to get all records from where id is 2.

declare @id int =(select id from dbo.Tb_Country where id=2)
Select * from dbo.Tb_Country where id > = @id


Sql query to get records after specific id:
I want to get all records after where id is 2.

Declare @ID int=2;
;WITH CTE
as
(
  select *, ROW_NUMBER() over (order by (select 0)) as rn
  from dbo.Tb_Country
)

select * from CTE where rn in(select rn + 1 from CTE where id >= @ID);


No comments:

Post a Comment