进来对事物作一下总结,常用代码如下:
--创建一个银行账户表 create table bank1 ( id int identity(1,1) not null primary key, CurrentMoney int not null check(CurrentMoney >1), CurrentName nvarchar(10) )
下面就是事物的操作:
declare @sum int set @sum =0 begin tran update bank1 set CurrentMoney = CurrentMoney -200 where CurrentName = 'zs' set @sum = @@error +@sum update bank1 set CurrentMoney = CurrentMoney+200 where CurrentName ='ls' set @sum =@@error +@sum if(@sum >0) begin rollback tran print 'Error' end else begin commit tran print 'OD' end
Create PROC Proc_Tran @money int, @fromName nvarchar(10), @toName nvarchar(10), @msg nvarchar(10) output as declare @errsum int set @errsum =0 begin tran update bank1 set CurrentMoney =CurrentMoney -@money where CurrentName =@fromName set @errsum=@errsum+@@error update bank1 set CurrentMoney =CurrentMoney +@money where CurrentName = @toName set @errsum =@errsum +@@error if(@errsum >0) begin rollback tran print 'Error' set @msg ='操作失败' end else begin commit tran print 'OK' set @msg ='操作成功' end declare @a nvarchar(10) exec Proc_Tran 10,'ls','zs' ,@msg =@a output print @a
ADO.NET的方面操作
代码
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
if(con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("Update bank1 set CurrentMoney = CurrentMoney - 200 where CurrentName ='"+this.txtFromName.Text.Trim()+"'",con);
SqlCommand cmd1 = new SqlCommand("update bank1 set CurrentMoney = CurrentMoney + 200 where CurrentName='"+this.txtToName.Trim()+"'",con);
SqlTransaction tran = con.BeginTransaction();//调用SqlConnection对象的BeginTransaction方法来实例化SqlTransaction对象
try
{
cmd.ExcuteNonQuery();
cmd1.ExcuteNonQuery();
tran.commit();
}
catch(SqlException ex)
{
tran.RollBack();
}
怀揣着一点点梦想的年轻人
相信技术和创新的力量
喜欢快速反应的工作节奏
相信技术和创新的力量
喜欢快速反应的工作节奏