SQL - How to track a field containing a sequence # from one stored proc and needed in another?

I have a stored proc that is using ROW_NUMBER to generate a specific sequence. Based on the last # generated, I need to use this # as a seed value in another stored proc to continue the sequence.

Is it possible to insert the last row number generated into a table? Is there a more elegant solution to this?

Thanks in advance!
nightshadzAsked:
Who is Participating?
 
Nakul VachhrajaniTechnical Architect, Capgemini IndiaCommented:
There are ways, but I am more worried about scaling up. How do you plan to handle things like multiple connections requesting the "next sequence" and one of them aborting or rolling back the transaction? Also, if each of these update the same column in a table, you will end up with large number of blocked transactions.

I would recommend evaluating the use of SEQUENCE, which is a new introduction in SQL Server 2012 (https://docs.microsoft.com/en-us/sql/t-sql/statements/create-sequence-transact-sql).
2
 
Pawan KumarDatabase ExpertCommented:
>>Is it possible to insert the last row number generated into a table? Is there a more elegant solution to this?
Yes it is possible.

CREATE TABLE GetFirstProcData( col1 Datatype , col2 datatype.... )
EXEC Proc1 ...parameter1, parameter2...

DECLARE @rnk AS BIGINT
SELECT @rnk  = MAX(rownumbercolumn) FROM GetFirstProcData

Pass this @rnk in the stored procedure 2 as an input parameter..

In second stored procedure 2..you have to write like below--

SELECT allcolumns, @rnk + ROW_NUMBER() OVER (PARTITION BY columns.....ORDER BY columns..) newrnk....
From yourtable..

 

Open in new window

0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
Nakul's suggestion of using SEQUENCE is a good one as you don't need to create tables and manage much code.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.