SCOPE_IDENTITY not returned by StoreProcedure

Posts   
 
    
kdekok
User
Posts: 26
Joined: 07-Apr-2008
# Posted on: 14-Apr-2011 16:42:26   

I need to have a sequence generator in SQL 2008, therefore i created a table with just one identity field and i use the following stored procedure named pGetNewSequence:


BEGIN
    INSERT INTO tSequence_Card default values;
    DELETE FROM tSequence_Card;
    return SCOPE_IDENTITY();
END

This is in LLBLGen mapped onto an ActionProcedure GetNewSequence, but whenever i invoke that procedure, the result is -1.

What is wrong here?

If i execute the procedure directly from SQL i get the actual new sequence nr, incrementing every time.

MTrinder
User
Posts: 1461
Joined: 08-Oct-2008
# Posted on: 14-Apr-2011 20:15:27   

You are not getting the value you expect returned as the return from the generated stored procedure call is actually the rowcount, if it is enabled on your server.

The way to do this it to use an output parameter. Change your stored proc to look something like this

ALTER PROCEDURE pGetNewSequence
@i int output
AS
BEGIN
    INSERT INTO tSequence_Card default values;
    DELETE FROM tSequence_Card;
    select @i = Scope_identity()
END
GO

and then call it like this...

int i=0;
ActionProcedures.PGetNewSequence(ref i);
MessageBox.Show(i.ToString( ));

Matt