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 ?)
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
AlertLogstable, if this has an identity.http://msdn.microsoft.com/en-us/library/ms190315.aspx