2

I have a stored procedure that reads the ID of a row with status x, then immediately sets that rows id to status y.

Since this stored procedure is being called by multiple client apps, somehow the same values are being returned whereas really it 2 executions should not find any in status x.

I'm not using anything other than wrapping the actions in a begin transaction / commit.

Rough example:

Begin Transaction
IF (@Param = '2') -- all
    BEGIN
        @resultID = (SELECT ... WHERE STATUS_ID = X
    END
ELSE
    BEGIN
        @resultID = (SELECT ... WHERE STATUS_ID = X
    END
IF (@ResultID > 0)
    BEGIN
        UPDATE JOB_QUEUE SET STATUS_ID = Y WHERE ID = @ResultID 
    END
COMMIT
SELECT * from JOB_QUEUE WHERE ID = @ResultID 

Somehow the query has returned the same @resultID from the table .. so I would presume I need some locking or something to prevent this.

Is there a method to ensure that executions of the stored procedure at the same time result in one executing and then the other (sequentially)?

Thanks.

3
  • 1
    Tag dbms product used. (Doesn't look like ANSI SQL...) Commented Nov 4, 2015 at 10:26
  • Which RDBMS is this for? Please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Commented Nov 4, 2015 at 10:33
  • HI this is for sql server Commented Nov 4, 2015 at 21:54

1 Answer 1

0

The simple answer is to speed up the whole process - if its a slow running query, then the select can run before the update is finished.

If you need to select the values for some other report, you could effectively run the update as the first statement, and use the OUTPUT keyword to return the ID's of the updated records eg:

UPDATE JOB_QUEUE
SET STATUS_ID = Y WHERE STATUS_ID = X
OUTPUT inserted.ID
Sign up to request clarification or add additional context in comments.

2 Comments

i need to retrieve an id based on paramers (changes the where clause) and then update that record id, and return the entire row.
i think you are right though, the select seems to be executed before the update is.. which is why i'm looking to hold all other hits on the stored proc until one single execution is complete.

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.