In a stored procedure, I'm executing an insert statement that affects many rows. I'd like to have it insert a unique id into each row (i.e. "60" into the first affected row, "61" into the second affected row, etc.) I do not want to use an identity field, rather I want to use an integer value contained in table NEXT_KEY_VAL with the following little stored procedure:
[tt]CREATE PROCEDURE GET_NEXT_KEY_VALUE
@KEY_NM VARCHAR(30), @NEXT_KEY_VAL INT = -1 OUTPUT
AS
SET NOCOUNT ON
UPDATE
NEXT_KEY_VAL WITH (ROWLOCK)
SET
@NEXT_KEY_VAL = KEY_VAL = KEY_VAL + 1
WHERE
KEY_NM = @KEY_NM
RETURN @NEXT_KEY_VAL[/tt]
I may not use an identity field because I need this id field to be valid across similar tables - therefore, I need to keep one system of numbering - which is the purpose of that stored procedure, above. The stored procedure is called like this: [tt] GET_NEXT_KEY_VALUE 'name_of_id'[/tt]
So the question is, is it possible to write the insert statement without using a loop to insert a unique value into each row it inserts?
i.e. [tt]insert into dbo.grant_info (grant_#, GET_NEXT_KEY_VALUE 'pi_id', grant_amt, org_id,...[/tt]
(I don't think that syntax works - but that's the idea.) I tried assigning GET_NEXT_KEY_VALUE into a variable and then putting that variable into my insert statement, but it inserted the same value into each and every affected record. (Which is, of course, obvious, after some thought.)
Thanks very much!
Lazer
[tt]CREATE PROCEDURE GET_NEXT_KEY_VALUE
@KEY_NM VARCHAR(30), @NEXT_KEY_VAL INT = -1 OUTPUT
AS
SET NOCOUNT ON
UPDATE
NEXT_KEY_VAL WITH (ROWLOCK)
SET
@NEXT_KEY_VAL = KEY_VAL = KEY_VAL + 1
WHERE
KEY_NM = @KEY_NM
RETURN @NEXT_KEY_VAL[/tt]
I may not use an identity field because I need this id field to be valid across similar tables - therefore, I need to keep one system of numbering - which is the purpose of that stored procedure, above. The stored procedure is called like this: [tt] GET_NEXT_KEY_VALUE 'name_of_id'[/tt]
So the question is, is it possible to write the insert statement without using a loop to insert a unique value into each row it inserts?
i.e. [tt]insert into dbo.grant_info (grant_#, GET_NEXT_KEY_VALUE 'pi_id', grant_amt, org_id,...[/tt]
(I don't think that syntax works - but that's the idea.) I tried assigning GET_NEXT_KEY_VALUE into a variable and then putting that variable into my insert statement, but it inserted the same value into each and every affected record. (Which is, of course, obvious, after some thought.)
Thanks very much!
Lazer