0

I'm trying to figure out how to combine INSERT FROM SELECT and returning id value of inserted record.

INSERT INTO [someDB].[dbo].[OBJ] ( column1, column2, column3 ) 
OUTPUT inserted.ID (SELECT TOP 1 590675, column2, column3 
                    FROM [someDB].[dbo].[OBJ] WHERE ID = 317817)
1
  • 3
    And what is your question? Commented Feb 5, 2018 at 9:54

2 Answers 2

1

If you are trying to get the new ID after your INSERT statement you can use SCOPE_IDENTITY, IDENT_CURRENT or @@IDENTITY. For example:

INSERT INTO [someDB].[dbo].[OBJ] ( column1, column2, column3 )

SELECT TOP 1
   590675,
   column2,
   column3
FROM [someDB].[dbo].[OBJ] WHERE ID = 317817
ORDER BY ...
SELECT SCOPE_IDENTITY(); -- Last identity generated in current session and current scope
SELECT @@IDENTITY; -- Last identity generated in current session across all scopes
SELECT IDENT_CURRENT([someDB].[dbo].[OBJ]) -- Last identity generated for the given table in any session and any scope

Because you are inserting just one row, SCOPE_IDENTIY() would be the best approach.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

0

Your syntax is a little wrong here.

You want:

INSERT INTO [someDB].[dbo].[OBJ] ( column1, column2, column3 )
OUTPUT inserted.ID
SELECT TOP 1
       590675,
       column2,
       column3
FROM [someDB].[dbo].[OBJ] WHERE ID = 317817
ORDER BY ...?; --You have a TOP 1, thus you really need an ORDER BY as well.

1 Comment

Thanks, bracket really should not be there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.