Hello I got some stored procedures to create products and other stuff on my site. Now I have to run some of them in a transaction. Is that possible or do I have to make a stored procedure only for the transaction?
Can I say something like
BEGIN TRAN
"1. stored procedure"
"2. stored procedure"
COMMIT
Yes, a stored procedure can be run inside a transaction.
Our scenario should be that If any of the INSERT statements fails to execute, no record should be inserted into any of the table. Notice the BEGIN TRAN statement that is creating a transaction scope. After that we are using BEGIN TRY statement where we are going to keep our INSERT statements that may throw errors.
This dba.stackexchange.com/a/46266/6548 gives a nice little demo of the fact that statements inside a stored proc are NOT within a single transaction; an implicit transaction is created for each individual statement.
PROC. Price Rate of Change (finance)
To add to the other answers above, you may want to add some error handling:
BEGIN TRAN BEGIN TRY EXEC P1 EXEC P2 COMMIT TRAN END TRY BEGIN CATCH ROLLBACK TRAN END CATCH
Update with C# code (I personally find it a lot easier to keep trans code out of the sprocs and in the data layer - makes composing stored procedures easier at a later stage):
using (var conn = new SqlConnection(...)) trans = conn.BeginTransaction(); try { ...call P1 using transaction ...call P2 using transaction trans.Commit(); } catch { trans.RollBack(); throw; } }
Yes, a stored procedure can be run inside a transaction. Please find below a sample query.
create table temp1
(
id int,
name varchar(20)
)
create table temp2
(
id int,
name varchar(20)
)
go
create proc p1 as
insert temp1 values (1, 'test1')
create proc p2 as
insert temp2 values (1, 'test2')
go
begin tran tx
exec p1
exec p2
commit
From SQL Server (not sure about other RDBMS), You can call multiple stored procedures inside a transaction.
BEGIN TRAN
EXEC StoredProc1
EXEC StoredProc2
COMMIT TRAN
You may want to add a return code to the stored proc to check if you should run stored proc 2 if stored proc 1 failed
EDIT: To check a return code you can do something like the following. This will run the first stored proc. If it returns 0 then it runs the 2nd. If the 2nd returns 0 then it commits the transaction. If either returns non-0 then it will rollback the transaction
DECLARE @ReturnValue INT
BEGIN TRAN
EXEC @ReturnValue = StoredProc1
IF @ReturnValue = 0
BEGIN
EXEC @ReturnValue = StoredProc2
IF @ReturnValue = 0
BEGIN
COMMIT
END
ELSE
BEGIN
ROLLBACK
END
END
ELSE
BEGIN
ROLLBACK
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With