yacine ouah yacine ouah - 1 year ago 101
SQL Question

How to get the value of autoincrement of last row at the insert

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

or a function to avoid the begin end transaction and select max

Answer Source


-- do insert


Which will give you:

The last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download