views:

5630

answers:

7

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:
http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row

+5  A: 

A question similar to this one was asked recently - Best way to get identity of inserted row?

Rob
+1  A: 

You have to select the scope_identity() function.

To do this from application code, I normally encapsulate this process in a stored procedure so it still looks like one query to my application.

Joel Coehoorn
+1  A: 

Scope_identity() is the preferred way, see: 6 Different Ways To Get The Current Identity Value

SQLMenace
+9  A: 

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.

Josh Hinman
This solution is good when only dealing with single row updates. For a good bulk update solution see kamajo's answer.
opadilla
+1  A: 

SCOPE_IDENTITY(); is your best bet. And if you are using .NET just pass an our parameter and check the value after the procedure is run.

CREATE PROCEDURE [dbo].[InsertProducts]
    @id    INT    = NULL OUT,
    @name   VARCHAR(150) = NULL,
    @desc   VARCHAR(250) = NULL

AS

    INSERT INTO dbo.Products
       (Name,
     Description)
    VALUES
       (@name,
     @desc)

    SET @id = SCOPE_IDENTITY();
David Basarab
+3  A: 

If you're inserting multiple rows the use of the OUTPUT and INSERTED.columnname clause on the insert statement is a simple way of getting all the ids into a temp table.

DECLARE @MyTableVar table( ID int,
Name varchar(50),
ModifiedDate datetime);
INSERT MyTable
OUTPUT INSERTED.ID, INSERTED.Name, INSERTED.ModifiedDate INTO @MyTableVar
SELECT someName, GetDate() from SomeTable

kamajo
I like this! Thanks for the tip.
opadilla
A: 

I tend to prefer attaching a trigger to the table using enterprise manager. That way you don't need to worry about writing out extra sql statements in your code. Mine look something like this:

Create Trigger tblName On dbo.tblName For Insert As select new_id = @@IDENTITY

Then, from within your code, treat your insert statements like select statements- Just execute and evaluate the results. the "newID" column will contain the identity of the row you just created.

callingshotgun