Sql Server 事务用法

继上一篇AspNetCore执行存储过程 - 点终将连成线 - 博客园 (cnblogs.com)中执行存储过程有个代码的事务:

 

 

 在后台存储过程也可以添加事务

实战用法:

Create PROCEDURE [dbo].[Procedure_RestoreData]
    
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    begin transaction tran_restore;
    declare @tran_error int;
    set @tran_error = 0;
    begin try
        delete table_name
        set @tran_error = @tran_error + @@error;
        update table *******
        set @tran_error = @tran_error + @@error;
        delete table_name
        set @tran_error = @tran_error + @@error;
    end try
    begin catch        
        print '出现异常,错误编号:' + convert(varchar, error_number()) + ', 错误消息:' + error_message(); 
        set @tran_error = @tran_error + 1;
    end catch
    if (@tran_error > 0)
        begin
            --执行出错,回滚事务
            rollback tran;
            select 0
        end
        else
        begin
            --没有异常,提交事务
            commit tran;
            select 1
        end
END

参考SQL Server 事务、异常和游标 - hoojo - 博客园 (cnblogs.com)

 

AspNetCore执行存储过程 - 点终将连成线 - 博客园 (cnblogs.com)
posted @ 2022-06-21 18:04  点终将连成线  阅读(139)  评论(0编辑  收藏  举报