>为什么需要触发器
use studb
go
if exists (select * from sysobjects where name = ''bank'')
drop table bank
if exists (select * from sysobjects where name = ''transinfo'')
drop table transinfo
create table bank
(
customername char(8) not null,
cardid char(10) not null,
currentmoney money not null
)
create table transinfo
(
cardid char(10) not null,
transtype char(4) not null,
transmoney money not null,
transdate datetime not null
)
go
alter table bank
add constraint ck_currentmoney check(currentmoney>=1)
alter table transinfo
add constraint df_transdate default(getdate()) for transdate
go
insert into bank (customername,cardid,currentmoney) value (''张三'',''001'',1000)
insert into bank (customername,cardid,currentmoney) value (''李四'',''002'',1)
insert into transinfo (cardid,transtype,transmoney) value (''001'',''支取'',200)
select * from bank
select * from transinfo
go
……………………………………………………………………………………………………………………………………
>创建INSERT触发器
use studb
go
if exists (select * from sysobjects where name = ''trigger_transinfo'')
drop trigger trigger_transinfo
create trigger trigger_transinfo
on transinfo
for insert
as
declare @type char(4),@outmoney money
declare @mycardid char(10),@balance money
select @type = transtype,@outmoney = transmoney,@mycardid = cardid from inserted
if (@type = ''支取'')
update bank set currentmoney = currentmoney - @outmoney
else
update bank set currentmoney = currentmoney + @outmoney
where cardid = @mycardid
print ''交易成功!交易金额:''+convert(varchar(20),@outmoney)
select @balance = currentmoney from bank where cardid = @mycardid
print ''卡号'' + @mycardid + '' 余额:'' + convert(varchar(20),@balance)
go
set nocount on -----不显示T-SQL语句影响的行数
insert into transinfo (cardid,transtype,transmoney) values (''001'',''支取'',200)
insert into transinfo (cardid,transtype,transmoney) values (''002'',''存入'',50000)
select * from bank
select * from transinfo
……………………………………………………………………………………………………………………………………
>创建DELETE触发器
use studb
go
if&n