Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedure - forcing execution order

I have a stored procedure that itself calls a list of other stored procedures in order:

CREATE PROCEDURE [dbo].[prSuperProc]

AS
BEGIN
    EXEC [dbo].[prProc1] 
    EXEC [dbo].[prProc2] 
    EXEC [dbo].[prProc3]
    --etc
END

However, I sometimes have some strange results in my tables, generated by prProc2, which is dependent on the results generated by prProc1. If I manually execute prProc1, prProc2, prProc3 in order then everything is fine. It appears that when I run the top-level procedure, that Proc2 is being executed before Proc1 has completed and committed its results to the db. It doesn't always go wrong, but it seems to go wrong when Proc1 has a long execution time (in this case ~10s).

How do I alter prSuperProc such that each procedure only executes once the preceding procedure has completed and committed? Transactions?

Edit for extra detail:

There is a table in my db which has a column which is null by default. prProc1 performs a set of update statements on this table to populate this column. prProc2 then inserts summary data into a secondary table based on the values in this column.

When I run the super procedure, what I am (sometimes) seeing is the first table has the results correctly calculated by prProc1, but prProc2 has generated results as though the column was all nulls. If I then manually run prProc2, the summary data is generated correctly.

like image 732
meepmeep Avatar asked Apr 21 '10 12:04

meepmeep


People also ask

Do stored procedures run sequentially?

We use a data migration flow that calls multiple SQL Server stored procedures sequentially and must be followed in this order. Our first procedure uses parameters to perform a check against our data and our next procedures only execute if the first procedure passes without returning failures.

Can I launch a stored procedure and immediately return without waiting for it to finish?

@Rachel - Yes.

Can a trigger execute a stored procedure?

A: Yes, we can call stored procedure inside the trigger.


1 Answers

Proc2 will not run before Proc1: it's a simple as that. SQL will execute one after the other but never out of order.

You can profile this using the TSQL_SPs template

Do you have 2 executions of the wrapper proc running, for example?

like image 67
gbn Avatar answered Oct 10 '22 01:10

gbn