创建事务
T-SQL中管理事务的语句:
1 开始事务: begin transaction
2 提交事务:commit transaction
3 回滚事务: rollback transaction
事务分类:
1 显式事务:用begin transaction明确指定事务的开始。
2 隐性事务:打开隐性事务:set implicit_transactions on,当以隐性事务模式操作时,SQL
Servler将在提交或回滚事务后自动启动新事务。无法描述事务的开始,只需要提交或回滚事务。
3 自动提交事务: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
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();
}
}
本文详细介绍T-SQL中事务的管理方式,包括开始、提交和回滚事务的具体语法,并通过两个具体示例展示了如何使用显式事务进行转账操作及批量插入数据,确保数据的一致性和完整性。
8579

被折叠的 条评论
为什么被折叠?



