Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server understand SCOPE_IDENTITY()

I have this piece of code in a stored procedure:

BEGIN
    SET @UserId = NULL;
    IF (@Username IS NOT NULL)
    BEGIN
        EXECUTE SP_ADD_USER @Username, @UserId OUTPUT;
    END
    EXECUTE SP_ADD_ALERT @Name, @AlertType, @AlertId OUTPUT;
    INSERT INTO AlertLogs (Datastamp, AlertID, UserID, NotificationMessage) 
        VALUES (@Datastamp, @AlertId, @UserId, @EmailMessage);
    SET @AlertLogId = SCOPE_IDENTITY();
END

@AlertLogId is an output parameter that I want to be assigned to the result of the last insert in AlertLogs table. Do I have to include

INSERT INTO AlertLogs (Datastamp, AlertID, UserID, NotificationMessage) 
        VALUES (@Datastamp, @AlertId, @UserId, @EmailMessage);

in a new block (a new begin/end scope) in order for SCOPE_IDENTITY() to work correctly ? (and not report for example the last ID of an inserted record done in SP_ADD_ALERT for example ?)

like image 363
Ghita Avatar asked Mar 15 '26 14:03

Ghita


1 Answers

In your query, SCOPE_IDENTITY() is going to return the last entered identity value into the database, for this scope.

In this instance, it will be the identity for the AlertLogs table, if this has an identity.

A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

http://msdn.microsoft.com/en-us/library/ms190315.aspx

like image 146
Curtis Avatar answered Mar 17 '26 05:03

Curtis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!