Reputation: 1290
I want to know if there is a way to state rollback the delete if I can not insert.
Please advice.
Something like below.
BEGIN TRAN
Delete from MYTABLE where ID=@ID;
INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME
COMMIT
Upvotes: 4
Views: 7992
Reputation: 26940
Turn xact_abort on to rollback the transaction on any error.
SET XACT_ABORT ON;
BEGIN TRAN
Delete from MYTABLE where ID=@ID;
INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME
COMMIT TRAN
Upvotes: 3
Reputation: 508
BEGIN TRAN
Delete from MYTABLE where ID=@ID;
INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME
if @@error = 0 and @@trancount > 0
commit
else
rollback
Upvotes: 0
Reputation: 20804
Here is another way to accomplish what you appear to be trying:
update myTable
set name = @name
where id = @id
Upvotes: 0
Reputation: 754538
You can put your two statements into a TRY....CATCH
block and only commit if both statements succeed:
BEGIN TRANSACTION
BEGIN TRY
DELETE FROM dbo.MYTABLE WHERE ID=@ID;
INSERT INTO dbo.MYTABLE (ID, NAME)
SELECT @ID, NAME
-- COMMIT only if both DELETE and INSERT worked ....
COMMIT TRANSACTION
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage
-- ROLLBACK if either DELETE and INSERT failed ....
ROLLBACK TRANSACTION
END CATCH
Upvotes: 10