I have a stored procedure that returns an unique Id. I need to call this sp to get the unique ID for each row. I must use this SP because an application also uses this.
How can I select for each row a ID that is returned from the SP?
CREATE procedure [dbo].[SelectNextNumber]
@TableName nvarchar(255)
as
begin
declare @NewSeqVal int
set NOCOUNT ON
update Number --This is a table that holds for each table the max ID
set @NewSeqVal = Next = Next + Increase
where TableNaam= @TableName
if @@rowcount = 0
begin
Insert into Number VALUES (@TableName, 1, 1)
return 1
end
return @NewSeqVal
The number table:
CREATE TABLE [dbo].[Number](
[TableName] [varchar](25) NOT NULL,
[Next] [int] NULL,
[Increase] [int] NULL
I have seen that a While loop is usable for this but in my situation I don’t know how to use a while loop.
Taking the singular INSERT INTO.. SELECT apart:
Temporarily store the SELECT results away
Store the rowcount and get that many numbers
For which you have to use the code in the SP directly:
Finally, the insert
ORDER by Col1is arbitrary, choose something sensible, or make itORDER BY NEWID()if you don’t care.