2

Database : SQL Server 2008

Is there a way to have an insert statement return a value in SQL Server,

There is a similar question in

Return a value from a insert statement , which talks about ORACLE .

I don't work with databases much, and not aware of ORACLE/SQL Server much, so sorry to ask it all over again.

For simplicity let me provide a small example :

The table EmpDetails has EmpiD and EmpName. The value of EmpID is autogenerated by the database.

INSERT INTO EMPDETAILS VALUES("John")

Now I want to get the value of EmpID associated with John

I don't want a stored procedure, I want a SQL statement only .

3
  • 1
    I wonder why you are so adamant about not wanting a stored procedure and returning scope_identity(). Commented Oct 19, 2011 at 17:02
  • @JonH I am not being adamant :-) The situation requires me to use a SQL statment. But feel free to post the SP too as a sidenot , maybe it might help me/others later. Commented Oct 19, 2011 at 17:05
  • No reason to post one, it would be a duplicate in the SO database, do a search plenty of articles / questions about it directly on this site. Commented Oct 19, 2011 at 17:09

1 Answer 1

9

Yes - you can use the little known and little used OUTPUT clause in your INSERT statement

INSERT INTO dbo.YourTable(col1, col2, col3, ...., ColN)
OUTPUT Inserted.Col1, Inserted.Col5, Inserted.ColN
VALUES(val1, val2, val3, ....., valN)

This returns a normal set of data, that you can deal with as you need to.

As the MSDN docs show, you can also send the OUTPUT values into e.g. a table variable or temp table for later use, if you need to.

To answer your updated question, use this:

INSERT INTO dbo.EMPDETAILS(EmpName)
OUTPUT Inserted.EmpID
VALUES("John")
Sign up to request clarification or add additional context in comments.

4 Comments

@JonH: yes, indeed - it's one of those "hidden gems" that a lot of developers overlook and don't know about...
@marc_s Thanks. I have updated my question, can you please provide me a sql statement for the EmpDetails table.
@Sujay Ghosh OUTPUT Inserted.ID
Is there a similar method for sqlite3?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.