Introduction:
Here I will explain how to get previous and next row values from sequence in sql server or find next and previous records from table in sql server or access previous and next row values from in sql server. To get next and previous records from table data in sql server we need to write query to get max and min value from table data based on value in sql server.
Here I will explain how to get previous and next row values from sequence in sql server or find next and previous records from table in sql server or access previous and next row values from in sql server. To get next and previous records from table data in sql server we need to write query to get max and min value from table data based on value in sql server.
Description:
In
previous articles I explained sql server get before and after character example, sql server keyboard shortcut keys, sql server order by with union example, SQL Server single procedure to
insert update delete, SQL Server take database backup, Primary key constraint in sql
server,
foreign key constraint in sql
server
and many articles relating to SQL
server.
Now I will explain how to get previous and next record value from table data in
sql
server.
In
one application I got requirement to get next and previous posts based on
current post from table in sql
server
but that record id values not in sequence. To get previous and next records
based on current record value I tried to get max and min value from sql
server
table based on current value like as shown below
SELECT (SELECT MAX(t.topicid) PreviousID
FROM @temp t
WHERE topicid < @ptopicid)
PreviousId, (SELECT MIN(et.topicid) NextID
FROM @temp et
WHERE topicid > @ptopicid)
NextId
|
If you observe above query we are getting previous
and next records based on current record id by taking max and min values in sql
server.
DECLARE @temp TABLE (topicid int, topicname varchar(50))
--Insert Data in table
INSERT INTO
@temp(topicid,
topicname)
values(1,'sql
joins'),
(5, 'sql insertion'),
(10,'sql creation'),
(13,'sql select'),
(16,'sql update'),
(24,'sql triggers')
DECLARE @ptopicid INT
SET @ptopicid = 10
-- Get Table Records
SELECT *
FROM @temp
-- Get Previous and Next Record Ids
SELECT (SELECT MAX(t.topicid) PreviousID
FROM @temp t
WHERE topicid < @ptopicid)
PreviousId, (SELECT MIN(et.topicid) NextID
FROM @temp et
WHERE topicid > @ptopicid)
NextId
|
If you observe above query we
insert data in temp table and getting previous and next record id values based
on topicid.
Output to Get Previous and Next Rows
Now we will run and see the output of above query that would be like as shown below
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
|
|||
0 comments :
Note: Only a member of this blog may post a comment.