12

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?

Community
  • 1
  • 1
Keith Maurino
  • 3,374
  • 10
  • 40
  • 48

7 Answers7

32

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
  • 6,745
  • 7
  • 38
  • 47
  • 3
    This solution is good when only dealing with single row updates. For a good bulk update solution see kamajo's answer. – CodeWarrior Jan 07 '10 at 18:57
  • 1
    For those looking how to do it with MySQL: just replace SCOPE_IDENTITY with LAST_INSERT_ID. Or simply use LastInsertedId parameter on the MySqlCommand; – Michael Olesen Oct 04 '11 at 14:14
  • I get an error casting the return value of ExecuteScalar() straight to an int. Works OK when I cast it to a decimal. – Adrian Toman Jul 07 '12 at 01:55
15

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  
Ray
  • 187,153
  • 97
  • 222
  • 204
kamajo
  • 574
  • 4
  • 5
  • BTW, not sure if it is version-specific (it's now 2012 and I'm on SQL 10.0.1600) but you don't have to go thru a temp table for this - you can just output directly. I also like that this works for GUID fields too, if they are used as PK... not that I advocate doing that so much, but it works. – Michael Bray May 10 '12 at 21:52
3

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

SQLMenace
  • 132,095
  • 25
  • 206
  • 225
3

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
  • 72,212
  • 42
  • 129
  • 156
1

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
  • 399,467
  • 113
  • 570
  • 794
1

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
  • 763
  • 2
  • 8
  • 17
0

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

Community
  • 1
  • 1
Udit Narayan
  • 109
  • 1
  • 7