dba123
asked on
How to obtain Identity of second insert
This below returns the just inserted Identity of the first insert. I want the scope to return the Identy of the second insert
INSERT INTO Users (AspNetUserID, Active, CreateUserID) VALUES (@NewUserId, 1, 0)
IF (NOT EXISTS (SELECT UserID from InstantForum414.dbo.Instan tASP_Users
WHERE InstantForum414.dbo.Instan tASP_Users .EmailAddr ess = @Email
OR InstantForum414.dbo.Instan tASP_Users .Username = @UserName))
BEGIN
INSERT INTO InstantForum414.dbo.Instan tASP_Users
(EmailAddress, Username, Password)
VALUES
(@Email, @UserName, @Password)
SET @NewForumUserID = SCOPE_IDENTITY()
INSERT INTO Users (AspNetUserID, Active, CreateUserID) VALUES (@NewUserId, 1, 0)
IF (NOT EXISTS (SELECT UserID from InstantForum414.dbo.Instan
WHERE InstantForum414.dbo.Instan
OR InstantForum414.dbo.Instan
BEGIN
INSERT INTO InstantForum414.dbo.Instan
(EmailAddress, Username, Password)
VALUES
(@Email, @UserName, @Password)
SET @NewForumUserID = SCOPE_IDENTITY()
ASKER
We already have a way to retrieve the NewUserID so I don't want to code something that is just going to act as a decal.
ASKER
Isn't there some sort of SCOPE_IDENTITY().Next whereas it knows to start from the first insert and go to the next based on the entire script.
IDENT_CURRENT('your_table' ) will return the last generated identity ... so you could use the return value plus 1 for the next identity
However, in there might be other thread getting the same number
However, in there might be other thread getting the same number
> However, in there might be other thread getting the same number
I mean in the case that you have concurrent connections executing your procedure at the same time ...
I mean in the case that you have concurrent connections executing your procedure at the same time ...
ASKER
that's not gonna work though. I am trying to get the Identity inserted into another database table. So there are possible conflicts using that as you suggested that I wan to stay away from.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
INSERT INTO Users (AspNetUserID, Active, CreateUserID) VALUES (@NewUserId, 1, 0)
SET @NewUserID = SCOPE_IDENTITY()
IF (NOT EXISTS (SELECT UserID from InstantForum414.dbo.Instan
WHERE InstantForum414.dbo.Instan
OR InstantForum414.dbo.Instan
BEGIN
INSERT INTO InstantForum414.dbo.Instan
(EmailAddress, Username, Password)
VALUES
(@Email, @UserName, @Password)
SET @NewForumUserID = SCOPE_IDENTITY()
END