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
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
Begin TRAN
BEGIN TRY
-- your Action
Commit TRAN
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRAN
END
END CATCH
Related
ALTER PROCEDURE Add_Edit_Courses_new
#CourseCode VARCHAR,
... other params ...
AS
BEGIN TRY
DECLARE #ErrorCode INT =0, #ErrorMessage VARCHAR(25) = 'Action failed'
IF #TaskType > 2
BEGIN
RAISERROR('Wrong action key',16,1)
END
ELSE
BEGIN TRANSACTION
BEGIN
DECLARE #message VARCHAR(MAX)
IF #TaskType = 1
BEGIN
INSERT INTO Courses(...) VALUES(#CourseCode,...)
SET #message = 'Added Successfully'
END
ELSE IF #TaskType = 2
BEGIN
UPDATE Courses SET CourseCode=#CourseCode,...;
SET #message = 'Modified Successfully'
END
END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT ERROR_NUMBER() AS ErrorNumber, ...
END CATCH
I wrote this stored procedure to insert and update and I used (1 & 2) to differentiate the task while using a try and catch, but every time I try to execute this stored procedure I keep getting that error, please can you help me with where I am wrong, I am just learning this principle for the first time.
Why is BEGIN TRANSACTION before BEGIN? I feel like BEGIN TRANSACTION/COMMIT TRANSACTION should be inside the ELSE conditional. With some noise removed:
IF #TaskType > 2
BEGIN
RAISERROR('Wrong action key',16,1);
END
ELSE
BEGIN -- moved this here
BEGIN TRANSACTION;
-- BEGIN -- removed this
DECLARE #message varchar(max);
IF #TaskType = 1
BEGIN
INSERT INTO Courses(...
SET #message = 'Added Successfully';
END
IF #TaskType = 2 -- don't really need ELSE there
BEGIN
UPDATE Courses SET ...
SET #message = 'Modified Successfully';
END
-- END -- removed this
COMMIT TRANSACTION;
SELECT #message;
END -- moved this here
In your catch you just blindly say:
ROLLBACK TRANSACTION;
This should be updated to:
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION;
END
Note that if you have a conditional where multiple statements are not wrapped correctly in BEGIN / END, they won't execute like you think. Consider:
IF 1 = 0
PRINT 'foo';
PRINT 'bar';
You get bar output every time, regardless of the result of the conditional.
You had something similar:
IF 1 = 1
-- do stuff
ELSE
BEGIN TRANSACTION;
BEGIN
-- do stuff
END
COMMIT TRANSACTION;
In that case, -- do stuff and the commit happened every time, even if the begin transaction did not, because that BEGIN/END wrapper (and anything that followed it) was not associated with the ELSE.
Perhaps a little dry and wordy if you're new to the topic, but Erland Sommarskog has a very comprehensive series on error handling here, might be worth a bookmark:
https://www.sommarskog.se/error_handling/Part1.html
https://www.sommarskog.se/error_handling/Part2.html
https://www.sommarskog.se/error_handling/Part3.html
Imo there are some major issues with this code. First, if the intention is for the transaction to be atomic then SET XACT_ABORT ON should be specified. Per the Docs RAISERROR does not honor SET XACT_ABORT ON so it could be converted to use THROW. Second, in cases where the ELSE block in the code is hit then COMMIT will always be hit (regardless of what happens to the commitable state of the transaction).
Also, the code performs the ROLLBACK before the code:
SELECT ERROR_NUMBER() AS ErrorNumber, ...
It's the ROLLBACK which clears the error messages and returns the state to normal. To catch the error metadata SELECT it before the ROLLBACK happens.
This is my stored procedure
ALTER Proc [dbo].[DeleteQualityAssemblyProduction]
#id int,
#Quantity int,
#idPartShip int,
#FK_idNextProcess int
AS
DELETE FROM [dbo].DailyQualityAssemblyProduction
WHERE id=#id
if #FK_idNextProcess=11
Begin
UPDATE [dbo].[ProjectShipping]
SET
QualityAssemblyQty = QualityAssemblyQty- #Quantity
WHERE id=#idPartShip
End
I want when both DELETE and UPDATE run successfully COMMIT the changes otherwise ROLLBACK .
I was wondering if adding COMMIT in the end of stored procedure do the job or I need other method
Here is one way you could tackle this. This is adding a transaction which you will need to handle multiple DML statements in one autonomous block. Then added a try/catch so that if either statement fails the transaction will deal with both statements as one unit of work.
ALTER Proc [dbo].[DeleteQualityAssemblyProduction]
(
#id int,
#Quantity int,
#idPartShip int,
#FK_idNextProcess int
) AS
set nocount on;
begin transaction
begin try
DELETE FROM [dbo].DailyQualityAssemblyProduction
WHERE id = #id
if #FK_idNextProcess = 11
begin
UPDATE [dbo].[ProjectShipping]
SET QualityAssemblyQty = QualityAssemblyQty - #Quantity
WHERE id = #idPartShip
end
commit transaction
end try
begin catch
rollback transaction
declare #error int
, #message varchar(4000);
select #error = ERROR_NUMBER()
, #message = ERROR_MESSAGE()
raiserror ('DeleteQualityAssemblyProduction: %d: %s', 16, 1, #error, #message) ;
end catch
I am writing a stored procedure which is going to be used for a sync in every 4 minutes. It is just a test case and I need to capture the exception in it as well. Is there any other way to use try and catch block in this procedure or this is fine ?
Here is the stored procedure :
Create procedure inbound_test
#APP1_NO int,
#APP1_NAME nvarchar (20),
#APP1_CREATED date,
#APP1_NO_PK nvarchar(20)
as
if exists (select App1_no from test_in1 where App1_no = #APP1_NO)
Begin try
Begin transaction
Update test_in1
set APP1_NO = #APP1_NO,
APP1_NAME = #APP1_NAME,
APP1_CREATED = #APP1_CREATED,
APP1_NO_PK = #APP1_NO_PK
where App1_no = #APP1_NO
Commit transaction
End try
Begin Catch
If ##Trancount > 0
Throw;
End Catch
else
If ##ROWCOUNT=0
Begin try
Begin Transaction
insert into test_in1(
APP1_NO ,
APP1_NAME ,
APP1_CREATED,
APP1_NO_PK
)
values ( #APP1_NO ,#APP1_NAME , #APP1_CREATED,#APP1_NO_PK)
Commit transaction
End try
Begin Catch
If ##Trancount >0
Throw;
End Catch
GO
Single update or Insert statement will be automatically in atomic transaction. You do not require explicit transaction to start and commit. If that statement is successful then it will be committed else it is already roll backed. Also you do not have explicit rollback in catch which is not necessary.
Also else block does not require another condition 'IF ##Rowcount>0' reason is that if it comes under else block it means that you have record for that value.
In Sql Server 2008 R2, I am creating a procedure with multiple transactions in it. Try..Catch Block is used for each transaction. I use output parameter to catch the error code and message since it will be caught by the main program. But When there is errors the output parameter are not correct set to the error message and code, what is problem here?
create procedure xxx (#P_Return_Status VARCHAR(1) OUTPUT, #P_Error_Code INT OUTPUT,)
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION TR1
.....
COMMIT TRANSACTIOn TR1
END TRY
BEGIN CATCH
IF (##TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION TR1
END
Set #P_Error_Code = Error_Number();
Set #P_Error_Messages = LEFT(ERROR_MESSAGE (), 2000)
END CATCH
BEGIN TRY
BEGIN TRANSACTION TR2
.....
COMMIT TRANSACTIOn TR2
END TRY
BEGIN CATCH
IF (##TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION TR2
END
Set #P_Error_Code = Error_Number();
Set #P_Error_Messages = LEFT(ERROR_MESSAGE (), 2000)
END CATCH
END
GO
Any help would be really appreciated!
I just don't see the point of putting two transaction inside this one procedure, just put all of the statements in one transaction and commit it or rollback it.
if it does need to be in separate transactions put these both try...catch in two separate procedures and call one sp from another sp's try block.
create procedure xxx
#P_Return_Status INT OUTPUT
,#P_Error_Code INT OUTPUT
,#P_Error_Messages VARCHAR(2000) OUTPUT
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION TR1
/* put statements from both transaction here
or
statements for TR1
AND
call the procedure containing code for TR2
*/
COMMIT TRANSACTIOn TR1
SET #P_Return_Status = 1;
END TRY
BEGIN CATCH
IF (##TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION TR1
END
Set #P_Error_Code = Error_Number();
Set #P_Error_Messages = LEFT(ERROR_MESSAGE (), 2000)
SET #P_Return_Status = 0;
END CATCH
END
GO
This is the first time that I use transactions and I just wonder am I make this right. Should I change something?
I insert post(wisp). When insert post I need to generate ID in commentableEntity table and insert that ID in wisp table.
ALTER PROCEDURE [dbo].[sp_CreateWisp]
#m_UserId uniqueidentifier,
#m_WispTypeId int,
#m_CreatedOnDate datetime,
#m_PrivacyTypeId int,
#m_WispText nvarchar(200)
AS
BEGIN TRANSACTION
DECLARE #wispId int
INSERT INTO dbo.tbl_Wisps
(UserId,WispTypeId,CreatedOnDate,PrivacyTypeId,WispText)
VALUES
(#m_UserId,#m_WispTypeId,#m_CreatedOnDate,#m_PrivacyTypeId,#m_WispText)
if ##ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error in adding new wisp.', 16, 1)
RETURN
END
SELECT #wispId = SCOPE_IDENTITY()
INSERT INTO dbo.tbl_CommentableEntity
(ItemId)
VALUES
(#wispId)
if ##ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error in adding commentable entity.', 16, 1)
RETURN
END
DECLARE #ceid int
select #ceid = SCOPE_IDENTITY()
UPDATE dbo.tbl_Wisps SET CommentableEntityId = #ceid WHERE WispId = #wispId
if ##ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error in adding wisp commentable entity id.', 16, 1)
RETURN
END
COMMIT
Using try/catch based on #gbn answer:
ALTER PROCEDURE [dbo].[sp_CreateWisp]
#m_UserId uniqueidentifier,
#m_WispTypeId int,
#m_CreatedOnDate datetime,
#m_PrivacyTypeId int,
#m_WispText nvarchar(200)
AS
SET XACT_ABORT, NOCOUNT ON
DECLARE #starttrancount int
BEGIN TRY
SELECT #starttrancount = ##TRANCOUNT
IF #starttrancount = 0
BEGIN TRANSACTION
DECLARE #wispId int
INSERT INTO dbo.tbl_Wisps
(UserId,WispTypeId,CreatedOnDate,PrivacyTypeId,WispText)
VALUES
(#m_UserId,#m_WispTypeId,#m_CreatedOnDate,#m_PrivacyTypeId,#m_WispText)
SELECT #wispId = SCOPE_IDENTITY()
INSERT INTO dbo.tbl_CommentableEntity
(ItemId)
VALUES
(#wispId)
DECLARE #ceid int
select #ceid = SCOPE_IDENTITY()
UPDATE dbo.tbl_Wisps SET CommentableEntityId = #ceid WHERE WispId = #wispId
IF #starttrancount = 0
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 AND #starttrancount = 0
ROLLBACK TRANSACTION
RAISERROR ('Error in adding new wisp', 16, 1)
END CATCH
GO
You'd use TRY/CATCH since SQL Server 2005+
Your rollback goes into the CATCH block but your code looks good otherwise (using SCOPE_IDENTITY() etc). I'd also use SET XACT_ABORT, NOCOUNT ON
This is my template: Nested stored procedures containing TRY CATCH ROLLBACK pattern?
Edit:
This allows for nested transactions as per DeveloperX's answer
This template also allows for higher level transactions as per Randy's comment
i think its not good all the time ,but if you want to use more than one stored procedure same time its not good be cause each stored procedure handles the transaction independently
but in this case,you should use try catch block , for exception handling , and preventing keeping transaction open on when an exception raising
I've never considered it a good idea to put transactions in a stored procedure. I think it's much better to start a transaction at a higher level so that can better coordinate multiple database (e.g. stored procedure) calls and treat them all as a single transaction.