Reputation: 1049
I have a table say scope_test as follows:
create table scope_test
(
id int identity(1,1),
val varchar(100)
)
Now when i insert a row in this table and select the scope identity through 2 different sql statements, i get to see a difference in performance of the 2 statements:
insert into scope_test values('abcd')
select scope_identity() -- statement 1
select scope_identity() from scope_test -- statement 2
statement 1 is faster than statement 2 according to the execution plan:
I am curios to know : 1. why is this difference in performance , and 2. Is it safe to use scope identity() as used in statement 1 i.e. without the table name ?
Upvotes: 0
Views: 1014
Reputation: 700352
The difference in performance is simply because you are doing different things. The second use of scope_identity
doesn't just get the last identity, it gets all records in the table and selects the value from scope_identity()
for each record in the table. You will just get the value from scope_identity()
once for each record that exists in the table.
So, the second use of scope_identity()
is simply pointless, it will return the same value one or more times (or zero times if the table used in the query would be empty). The value of scope_identity()
is not at all related to the table that you use in the query, i.e. if you insert records in different tables you can't use it to get the last id inserted in a specific table.
Upvotes: 4