I have googled this problem one week and no thing useful I think am not using the correct word
I am using SQL Server 2008 with t-sql and my need is to optimise my function when I insert a new row.
I have a table with first column is the key of integer autoincrement type and other columns are just for information
When we do an insert, SQL Server increments the key automatically and I have to do a select max to get the value, so is there a way like a global variable like @@IDENTITY
or a function to avoid the begin end transaction and select max
If you are using MySQL you get the auto increment ID of the last insert with:
SELECT LAST_INSERT_ID();
See here for full reference.
In my case I had to use @@Identity, because I was inserting into a view. It seems that SCOPE_IDENTITY only works for ones you have explicitly created.
See here:
http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
What about this for last auto increment value
Use
SCOPE_IDENTITY
:Which will give you:
Just ran the code:
and it also works!