Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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  

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

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();

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.

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.

This is probably the best working solution I found for SQL Server.. Sql Server return the value of identity column after insert statement

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top