简体   繁体   中英

Using SCOPE_IDENTITY result in another query

I'm having difficulties with this code

EXECUTE Environment.dbo.psu_some_psu

@instanceId = 1
,@serverId = 2
,@ip = '111.111.111.111'
,@clientName = 'dev-contact'
,@applicationId = 9
,@accountId = 35
,@userID = 22

DECLARE @restoreId INT
SET @restoreId = SCOPE_IDENTITY()

UPDATE Environment.dbo.restore_requests
SET Status = 1
WHERE Id = @restoreId

The stored procedure insert a row with indentity and with a status by default. After the execution of the stored procedure i use scope_identity to get the ID of the inserted row. But i cant get the update to work, i think there is a problem with the WHERE condition.

Thanks

It's called SCOPE_IDENTITY() because it returns the last identity value inserted in the current scope - and since each procedure has it's own scope - you do not get the expected results.

Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope.

Use an output parameter to return the scope_identity() from inside the procedure that actually executes the insert statement.

Also, please note that if you are inserting multiple records, the scope_identity() will return only the last value - in such cases you use the output clause on the insert statement to get a table containing all the newly inserted identity values.

DECLARE @MyTableVar table( NewScrapReasonID smallint,  
                           Name varchar(50),  
                           ModifiedDate datetime);  
INSERT Production.ScrapReason  
    OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate  
        INTO @MyTableVar  
VALUES (N'Operator error', GETDATE());  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM