小白求帮助。。。。
银行业务数据库bankdb,其中,帐户信息表(bank)存放帐户的信息,交易信息表(transInfo)存放每次的交易信息。怎么建立触发器使转账时候能自动更新transInfo表呢?
create database bankdb
create table bank(
customerName varchar(255),
cardID char(10) primary key,
currentMoney smallmoney
)
create table transInfo(
transDate datetime,
cardID char(10) primary key,
transType char(4),
transMoney smallmoney,
)
insert into bank(customerName,cardID,currentMoney)values('张三','1001 0001',1000.0000)
insert into bank(customerName,cardID,currentMoney)values('李四','1001 0002',1.0000)
create trigger bank_info on bank for update
as
declare @Money1 smallmoney
declare @Money2 smallmoney
declare @M smallmoney
@Money1=(select currentMoney from deleted),
@Money2=(select currentMoney from inserted)
from transInfo,deleted,inserted
if(@Money1>@Money2)
update transInfo
set transType='支出',@M=@Money1-@Money2
if(@Money1<@Money2)
update transInfo
set transType='支入',@M=@Money2-@Money1
update transInfo set transMoney=@M
update transInfo set transDate=(select getdate())
update transInfo set cardID=(select cardID from deleted)
BEGIN TRANSACTION
/*--定义变量,用于累计事务执行过程中的错误--*/
DECLARE @errorSum INT
SET @errorSum=0 --初始化为0,即无错误
/*--转帐:张三的帐户少1000元,李四的帐户多1000元*/
UPDATE bank SET currentMoney=currentMoney-1000
WHERE customerName='张三'
SET @errorSum=@errorSum+@@error
UPDATE bank SET currentMoney=currentMoney+1000
WHERE customerName='李四'
SET @errorSum=@errorSum+@@error --累计是否有错误
IF @errorSum<>0 --如果有错误
BEGIN
print '交易失败,滚回事务'
ROLLBACK TRANSACTION
END
ELSE
BEGIN
print '交易成功,提交事务,写入硬盘,永久的保存'
COMMIT TRANSACTION
END
GO
print '查看转帐事务后的余额'
SELECT * FROM bank
GO
我的触发器好像。。。求帮助
------解决方案--------------------
--table ta tb
update b
set b.totalMoney = b.totalMoney +
(case when a.transType when 'out' then -a.setMoney else a.setMoney end)
from ta a join tb b on a.cardID = b.cardID
--这里没有考虑支出金额大于现存金额的问题!