Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCOPE_IDENTITY, multiple inserts, carries value from previous insert if current insert doesn't insert

Tags:

sql

sql-server

**Edit: RESOLVED - Thank you all! I can't 'vote up' any of your replies due to my low rep, but I appreciate them all!

Edit 2: Rep high enough now, vote up's to all!**

ok, I have a sproc that runs a few inserts, assigning the new record identity to a variable, then inserting those into another table. The issue is that some of the inserts don't insert (if no data to insert) but the SCOPE_IDENTITY(); carries from the previous insert...

in the code below, I would expect @NewId2 to be null, but it contains the id from the previous insert. What should I do to prevent @NewId2 from having the "wrong Id?"

CREATE TABLE #tempdemo (
theId int IDENTITY(100,3),
theField varchar(20)
)

DECLARE @NewId1 int
DECLARE @NewId2 int

INSERT INTO 
#tempdemo
    (theField)
SELECT
    'test1'
--this would have a "from table" in a real situation
WHERE
    1 = 1

SET @NewId1 = SCOPE_IDENTITY();

INSERT INTO 
#tempdemo
    (theField)
SELECT
    'test2'
--this would have a "from table" in a real situation
WHERE
    1 = 2 --obviously fails, in my real situation there are times the insert has nothing to insert

SET @NewId2 = SCOPE_IDENTITY();


select '@NewId1 = ', @NewId1, '@NewId2 = ', @NewId2


drop table #tempdemo
like image 423
msimmons Avatar asked Dec 15 '22 20:12

msimmons


1 Answers

After you insert, save scope_identity() in a variable if @@rowcount is greater than 0.

EX:

DECLARE @MY_NEW_ID INT

INSERT INTO TABLE2 (COL1)
SELECT VAL1
FROM TABLE1
WHERE X=Y

IF @@ROWCOUNT>0
BEGIN
   SET @MY_NEW_ID  = SCOPE_IDENTITY()
END

/* DO MORE INSERTS HERE ... */

IF @MY_NEW_ID IS NOT NULL
BEGIN
   INSERT INTO TABLE3 (NEWID) VALUES @MY_NEW_ID  
END
like image 71
Dave Cullum Avatar answered May 16 '23 04:05

Dave Cullum