1

I have a stored proc with two insert statements. I would like to return the ID from the first insert. It looks broadly like this:

declare @retVal int
Begin transaction

insert into myTable(..) values (..)

set @retVal = scope_identity()

insert into myTable2(..) values(..)

Commit transaction

return @retVal

When I do this, the insert statements work fine but the same value is returned every time (in this case, ID 6 from myTable, for some strange reason.)

Would anyone have a guess on what's going on?

16
  • 2
    Or use an output parameter... Commented Mar 7, 2013 at 18:49
  • 2
    @Thomas why do you think SELECT is better? You want to require all the scaffolding of retrieving a resultset, potentially using a DataReader, etc. to retrieve a single, scalar value? OUTPUT is far more appropriate in this case. Commented Mar 7, 2013 at 18:50
  • 1
    Is the ID column on myTable an IDENTITY column or is the ID created/populated via a trigger? Commented Mar 7, 2013 at 19:13
  • 2
    Agreed output param is the right way to do it, but nothing syntactically wrong w/ return in his script. Definitely nothing that would return 6. Simply changing to select instead of return is unlikely to fix it. Need to see the full picture. Commented Mar 7, 2013 at 19:24
  • 1
    So, @larryq, is there a trigger on myTable? Could you share it? Could you also share the code where you are retrieving the return value and seeing 6 every time? Commented Mar 7, 2013 at 19:28

1 Answer 1

7

Please use an OUTPUT parameter. RETURN is for returning status/error codes, not data. For example, RETURN only handles INT. Guess what happens when you change your table to use BIGINT because INT wasn't enough?

ALTER PROCEDURE dbo.YourProcedure
  @params VARCHAR(32),
  @Table1ID INT = NULL OUTPUT
AS
BEGIN
  SET NOCOUNT ON;

  BEGIN TRANSACTION;

  INSERT dbo.Table1...
  SET @Table1ID = SCOPE_IDENTITY();
  INSERT dbo.Table2...

  COMMIT TRANSACTION;
END
GO
Sign up to request clarification or add additional context in comments.

3 Comments

Using an output parameter did the trick, thanks very much to everyone. I'm happy to go that route from here on.
It returning both @Table1ID value and RETURN value... how to supress only the Table1ID ?
Sorry @bhat, I don't understand the issue. Maybe you should create a new question.

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.