0

I did some research and found out that the best solution to get the id of newly inserted row is output clause.I am using the insert statement output clause for the first time and couldnt figure it out.

here is my sql code. what is wrong with this sql?

ALTER PROCEDURE [dbo].[MedBul_Insert_Message]      
                                              (@ParentID int, @MessageFrom varchar(500),@MessageTo varchar(500), @MessageSubject varchar(500),@MessageBody varchar(4000),@MessageIsRead int)
AS
BEGIN
    SET LANGUAGE Turkish;

Declare @message_id table (MessageID int);

insert into Messages output INSERTED.ID INTO @message_id (ParentID ,MessageFrom ,MessageSubject ,MessageBody ,MessageIsRead ) values(@ParentID ,@MessageFrom ,@MessageSubject ,@MessageBody ,@MessageIsRead );


END
2
  • "Doesn't work" - in what way? An error message? If so, what? Commented Apr 19, 2013 at 7:25
  • it gives this error: Column name or number of supplied values does not match table definition. Commented Apr 19, 2013 at 7:26

1 Answer 1

5

The OUTPUT clause should come after the column list:

insert into Messages (ParentID ,MessageFrom ,MessageSubject ,MessageBody ,MessageIsRead )
output INSERTED.ID INTO @message_id (MessageID)
values(@ParentID ,@MessageFrom ,@MessageSubject ,@MessageBody ,@MessageIsRead );

See the INSERT documentation.

(And also, obviously, you need to actually do something with the contents of @message_id now, but I presume you've not yet written or just not shown in your question, the remainder of the stored procedure)

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

5 Comments

yes, and I was going to ask you help me to insert that message_id into another table :)
I need to write another insert statement to insert that id, can you give me a short example for that?
Work out what you want to insert into the next table as a SELECT statement, using @message_id as one of the tables in the FROM clause. You can then use INSERT (...) SELECT ... instead of INSERT (...) VALUES () to change that SELECT into an INSERT.
my second insert statement is easy but I dont know how to do it? here is the insert "insert into MessagesTo (MessageID,ToProfessionalID) values()"
Technically you don't need to output into anything either, just having the output statement will return the values as expected. Here's a code example

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.