如果执行错误,则撤消存储过程

时间:2018-06-25 08:40:57

标签: sql-server

alter proc insert_toplam 'deneme2'
@str nvarchar(100)
as
begin
    insert into tblSekiller(sekilURL)
    select @str

    insert into tbl_fake
    select @str
end

我想要阻止过程插入table_1,如果过程以某种方式在行insert into tbl_fake上给出错误,可以吗?

1 个答案:

答案 0 :(得分:4)

您可以使用TRY-CATCH并执行以下操作:

BEGIN TRANSACTION;  

BEGIN TRY  

INSERT INTO tblSekiller(sekilURL)
SELECT @str

INSERT INTO tbl_fake
SELECT @str

END TRY  
BEGIN CATCH  
    IF @@TRANCOUNT > 0  
        ROLLBACK TRANSACTION; -- if your insert generated an error, rollback  
END CATCH;  

IF @@TRANCOUNT > 0  
    COMMIT TRANSACTION;  -- otherwise, commit the transaction
GO