当前位置: 代码迷 >> Sql Server >> 有关SQL语句的批处理机制。该怎么解决
  详细解决方案

有关SQL语句的批处理机制。该怎么解决

热度:65   发布时间:2016-04-27 17:01:54.0
有关SQL语句的批处理机制。
我有一个存储过程,里面包含了两句T-SQL语句。
CREATE   PROCEDURE   abc
      @id   varchar(30)   AS  
insert   tb1(id,name)   SELECT   id,name   from   tb2   where   [email protected]
delete   from   tb2   where   [email protected]
go

因为id是tb1的唯一索引,索引当在tb1中插入重复id时会提示出错,insert语句插入失败。可是奇怪的是后面的delete语句还是执行了。结果插入失败而删除却成功了。
怎样让这两个语句作为一个整体来运行,插入失败就退出,不要删除了。

------解决方案--------------------
加事务就行了.

CREATE PROCEDURE abc
@id varchar(30) AS
set xact_abort on
begin tran
insert tb1(id,name) SELECT id,name from tb2 where [email protected]
delete from tb2 where [email protected]
commit tran
go
  相关解决方案