I know that the SCOPE_IDENTITY()
will get the last inserted row from insert statement. However, for the following case, I am not too sure is SCOPE_IDENTITY()
is safe. As SELECT MAX(ID) FROM TableA
will have go through scan the table to get the max id and it will have performance issue, even slightly, I believe.
Here is the case:
DECLARE @DaysInMonth INT
DECLARE @FirstID INT
DECLARE @SecondID INT
DECLARE @ThirdID INT
DECLARE @FourthID INT
SET @DaysInMonth = DAY(EOMONTH('2016-09-01'))
BEGIN TRY
BEGIN TRANSACTION
WHILE @DaysInMonth > 0
BEGIN
-- First Insert -- Begin
INSERT INTO tableA ('first insert - ' + @DaysInMonth)
-- First Insert -- End
SET @FirstID = SCOPE_IDENTITY()
-- Second Insert -- Begin
INSERT INTO tableB ('second insert - ' + @DaysInMonth)
-- Second Insert -- End
SET @SecondID = SCOPE_IDENTITY()
-- Third Insert -- Begin
INSERT INTO tableC ('third insert - ' + @DaysInMonth)
-- Third Insert -- End
SET @ThirdID = SCOPE_IDENTITY()
-- Fourth Insert -- Begin
INSERT INTO tableD ('fourth insert - ' + @DaysInMonth)
-- Fourth Insert -- End
SET @FourthID = SCOPE_IDENTITY()
SET @DaysInMonth = @DaysInMonth - 1
END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION
THROW
END CATCH
As from the case above, I have to insert the records every loop for fourth times for how many days in the month that I have declared.
From what I know, there are 4 to get the last inserted ID:
- SCOPE_IDENTITY
- @@IDENTITY
- SELECT MAX(ID) FROM tableA
- IDENT_CURRENT
From the following post: Post
Is mentioned that SCOPE_IDENTITY()
is what generally that you want to use.
What I mean with 'Safe' is, do the ID will be unique during the loop?
Thank you.