if exists (select * from sys.databases where name='TestDB')
drop database TestDB;
create database TestDB;
use TestDB;
if OBJECT_ID('department','U') is not null
drop table department
create table department
(
id int primary key identity(1,1),
name varchar(20) not null,
num varchar(50) not null
)
if OBJECT_ID('employee','U') is not null
drop table employee;
create table employee
(
id int primary key identity(1,1) ,
name nvarchar(30) not null,
departmentId int foreign key references department(id) not null
)
insert into employee(name)values('zhangsan')
select * from employee;
select * from department;select * from employee;
select * from department;
begin transaction
declare @errorSum int
set @errorSum = 0
insert into department(name,num)
values('软件一部','001')
insert into employee(name,departmentId)
values ('lishi','1')
set @errorSum =@errorSum + @@error --累加错误到变量@errorSum中
if @errorSum <>0
begin
print '------------------回滚事务--------------------------'
rollback transaction
end
else
begin
print '------------------提交事务---------------------------'
commit transaction
end