Sql-server – In SQL Server is it possible to get “id” of a record when Insert is executed

identitysql server

In SQL Server 2005 I have an "id" field in a table that has the "Is Identity" property set to 'Yes'. So, when an Insert is executed on that table the "id" gets set automatically to the next incrementing integer. Is there an easy way when the Insert is executed to get what the "id" was set to without having to do a Select statement right after the Insert?

duplicate of:
Best way to get identity of inserted row?

Best Answer

In .Net at least, you can send multiple queries to the server in one go. I do this in my app:

command.CommandText = "INSERT INTO [Employee] (Name) VALUES (@Name); SELECT SCOPE_IDENTITY()";
int id = (int)command.ExecuteScalar();

Works like a charm.