高手请进:关于SQL的事务处理

rocllllll 2003-11-06 11:49:42
例如在一存储过程中,语句如下(伪代码)
update a.....
update b.....
update c.....
update d.....
update e.....
update f.....
要求:只要中间有任意一个SQL出错,整个事务全部返回
...全文
42 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
rocllllll 2003-11-06
  • 打赏
  • 举报
回复
正是对不起,我弄错了,谢谢二位!结贴
pengdali 2003-11-06
  • 打赏
  • 举报
回复
你不放心就:

begin tran
update a.....
if @@error<>0 goto error
update b.....
if @@error<>0 goto error
update c.....
if @@error<>0 goto error
update d.....
if @@error<>0 goto error
update e.....
if @@error<>0 goto error
update f.....
if @@error<>0 goto error
commit tran
return

error:
rollback tran
pengdali 2003-11-06
  • 打赏
  • 举报
回复
是呀他自动会会滚的。你执行
select * from #table1
看呀。
伍子V5 2003-11-06
  • 打赏
  • 举报
回复
SET XACT_ABORT
指定当 Transact-SQL 语句产生运行时错误时,Microsoft® SQL Server™ 是否自动回滚当前事务。

语法
SET XACT_ABORT { ON | OFF }

注释
当 SET XACT_ABORT 为 ON 时,如果 Transact-SQL 语句产生运行时错误,整个事务将终止并回滚。为 OFF 时,只回滚产生错误的 Transact-SQL 语句,而事务将继续进行处理。编译错误(如语法错误)不受 SET XACT_ABORT 的影响。

对于大多数 OLE DB 提供程序(包括 SQL Server),隐性或显式事务中的数据修改语句必须将 XACT_ABORT 设置为 ON。唯一不需要该选项的情况是提供程序支持嵌套事务时。有关更多信息,请参见分布式查询和分布式事务。

SET XACT_ABORT 的设置是在执行或运行时设置,而不是在分析时设置。

示例
下例导致在含有其它 Transact-SQL 语句的事务中发生违反外键错误。在第一个语句集中产生错误,但其它语句均成功执行且事务成功提交。在第二个语句集中,SET XACT_ABORT 设置为 ON。这导致语句错误使批处理终止,并使事务回滚。

CREATE TABLE t1 (a int PRIMARY KEY)
CREATE TABLE t2 (a int REFERENCES t1(a))
GO
INSERT INTO t1 VALUES (1)
INSERT INTO t1 VALUES (3)
INSERT INTO t1 VALUES (4)
INSERT INTO t1 VALUES (6)
GO
SET XACT_ABORT OFF
GO
BEGIN TRAN
INSERT INTO t2 VALUES (1)
INSERT INTO t2 VALUES (2) /* Foreign key error */
INSERT INTO t2 VALUES (3)
COMMIT TRAN
GO

SET XACT_ABORT ON
GO

BEGIN TRAN
INSERT INTO t2 VALUES (4)
INSERT INTO t2 VALUES (5) /* Foreign key error */
INSERT INTO t2 VALUES (6)
COMMIT TRAN
GO

/* Select shows only keys 1 and 3 added.
Key 2 insert failed and was rolled back, but
XACT_ABORT was OFF and rest of transaction
succeeded.
Key 5 insert error with XACT_ABORT ON caused
all of the second transaction to roll back. */

SELECT *
FROM t2
GO

DROP TABLE t2
DROP TABLE t1
GO

rocllllll 2003-11-06
  • 打赏
  • 举报
回复
请教大力:
create table #Table1 (a tinyint)
go
begin tran
insert #table1 values(1) ----成功
insert #table1 values(1000) ----这句将报错
commit tran
在1000报错之后,1仍然插了进去,我要求1也回滚,请帮帮忙!!!
pengdali 2003-11-06
  • 打赏
  • 举报
回复
举例:

SET XACT_ABORT on ----设置
go

create table #Table1 (a tinyint)
go
begin tran
insert #table1 values(1) ----成功
insert #table1 values(1000) ----这句将报错
commit tran
go
select * from #table1
go
drop table #table1
pengdali 2003-11-06
  • 打赏
  • 举报
回复
begin tran
update a.....
update b.....
update c.....
update d.....
update e.....
update f.....
commit tran

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧