SqlServer事务使用方法

本文详细介绍T-SQL中事务的管理方式,包括开始、提交和回滚事务的具体语法,并通过两个具体示例展示了如何使用显式事务进行转账操作及批量插入数据,确保数据的一致性和完整性。

创建事务
T-SQL中管理事务的语句:
开始事务: begin transaction
提交事务:commit transaction
回滚事务: rollback transaction
事务分类:
显式事务:begin transaction明确指定事务的开始。
隐性事务:打开隐性事务:set implicit_transactions on,当以隐性事务模式操作时,SQL Servler将在提交或回滚事务后自动启动新事务。无法描述事务的开始,只需要提交或回滚事务。
自动提交事务:SQL Server的默认模式,它将每条单独的T-SQL语句视为一个事务。如果成功执行,则自动提交,否则回滚。

示例:张三转800元到李四帐户上。
 
use stuDB
go
--创建帐户表bank--
if exists(select* from sysobjects where name='bank')
    drop table bank
create table bank
(
    customerName char(10),    --顾客姓名
    currentMoney money        --当前余额
)
go
/*--添加约束,帐户不能少于元--*/
alter table bank add
        constraint CK_currentMoney check(currentMoney>=1)
/*--插入测试数据--*/
insert into bank(customerName,currentMoney)
select '张三',1000 union
select '李四',1

select * from bank
go

/*--使用事务--*/
use stuDB
go
--恢复原来的数据
--update bank set currentMoney=currentMoney-1000 where customerName='李'
set nocount on    --不显示受影响的行数
print '查看转帐事务前的余额'
select * from bank
go

/*--开始事务--*/
begin transaction
declare @errorSum int    --定义变量,用于累计事务执行过程中的错误
/*--转帐--*/
update bank set currentMoney=currentMoney-800 where customerName='张三'
set @errorSum=@errorSum+@@error    --累计是否有错误
update bank set currentMoney=currentMoney+800 where customerName='李四'
set @errorSum=@errorSum+@@error --累计是否有错误

print '查看转帐事务过程中的余额'
select * from bank

/*--根据是否有错误,确定事务是提交还是回滚--*/
if @errorSum>0
    begin
        print '交易失败,回滚事务.'
        rollback transaction
    end
else
    begin
        print '交易成功,提交事务,写入硬盘,永久保存!'
        commit transaction
    end
go

print '查看转帐后的余额'
select * from bank
go


SqlServer事务实例2

UserInfo表结构如图: 
这里写图片描述 
事务代码1:

begin tran tran_AddUserInfo --开始事务

declare @tran_error int;
set @tran_error=0;
begin try
  insert into dbo.UserInfo values(2016009,'aaa','2016-08-19 09:13:41.227','男')
  insert into dbo.UserInfo values(2016009,'bbb','2016-08-19 09:13:41.227','哼哼哼')
  insert into dbo.UserInfo values(2016009,'ccc','2016-08-19 09:13:41.227','哈哈哈')
end try
begin catch
  set @tran_error=@tran_error+1; --加分号或不加都能正常执行
end catch
if(@tran_error>0)
begin
  rollback tran tran_AddUserInfo; --执行出错,回滚事务(指定事务名称)
  print @tran_error;
end 
else
begin
  commit tran tran_AddUserInfo; --没有异常,提交事务(指定事务名称)
  print @tran_error;
end

事务代码2:

begin tran tran_AddUserInfo --开始事务

declare @tran_error int;
set @tran_error=0;
begin try
  insert into dbo.UserInfo values(2016009,'aaa','2016-08-19 09:13:41.227','男')
  insert into dbo.UserInfo values(2016009,'bbb','2016-08-19 09:13:41.227','哈哈')
  insert into dbo.UserInfo values(2016009,'ccc','2016-08-19 09:13:41.227','哈哈')
end try
begin catch
  set @tran_error=@tran_error+1; --加分号或不加都能正常执行
end catch
if(@tran_error>0)
begin
  rollback tran; --执行出错,回滚事务(不指定事务名称)
  print @tran_error;
end 
else
begin
  commit tran; --没有异常,提交事务(不指定事务名称)
  print @tran_error;
end
C#后台代码拼Sql事务语句


public partial class TestSqlTran : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            Execute();
        }
    }
    private void Execute()
    {
        string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();
        SqlConnection connection = new SqlConnection(connString);
        StringBuilder sqlSB=new StringBuilder();
        /*sqlSB.AppendLine("begin tran tran_handle")与SqlServer中的换行不是一回事,
          C#后台每行Sql语句后边必须加空格分隔,
          不能用sqlSB.AppendLine("begin tran tran_handle")来替代sqlSB.Append("begin tran tran_handle ")          
        */
        sqlSB.Append("begin tran tran_handle ");
        sqlSB.AppendFormat("declare {0} int;set {0}=0;", "@tran_error");                
        sqlSB.Append("begin try ");
        sqlSB.AppendFormat("delete from Descriptions where Id='{0}' ", "1");
        sqlSB.Append("end try ");
        sqlSB.Append("begin catch ");
        //set @tran_error=@tran_error+1;以分号结尾可以不用空格
        sqlSB.Append("set @tran_error=@tran_error+1;");
        sqlSB.Append("end catch ");
        sqlSB.Append("if(@tran_error>0) begin rollback tran; end ");
        sqlSB.Append("else begin commit tran; end ");
        SqlCommand cmd=new SqlCommand(sqlSB.ToString(),connection);
        connection.Open();
        int count = cmd.ExecuteNonQuery();
        connection.Close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值