日期:2014-05-18  浏览次数:20472 次

sql server 中能否实现这样的 触发器?
表 uesr

ID(主码) name money

1 张三 500
2 李四 200
3 王五 400


表 opera

服务号(主码) ID(是上表ID的外码) mark(标记,只能取值为“存款”或者“取款”) change(本次操作的金额)

1 李四 存款 900
2 王五 取款 100


要求建立触发器,实现下面功能:

1、只要在表opera中插入一行新的数据,首先判断,如果是取款,就到表 uesr中找到对应用户的当前金额,如果要取得金额大于此人现有的金额则禁止插入这条交易记录

2、如果是一条合法的交易记录。那么,要更新存取款后的,表uesr中对应客户的现有金额记录

------解决方案--------------------
SQL code


create trigger tr_ins_opera on opera
instead of insert
as
begin
    if exists (select 1 from inserted where mark='取款')
    begin
        if exists (select 1 from inserted a inner join uesr b on a.id = b.id and a.mark='取款' and a.change>b.money)
        begin
            print '超出取款金额'
            rollback tran
        end
        
        update uesr set money = money - change
        from uesr a inner join inserted b on a.id = b.id and b.mark='取款'
    
    end
    
    if exists (select 1 from inserted where mark='存款' )
    begin
        update uesr set money = money + change
        from uesr a inner join inserted b on a.ID = b.id and b.mark='存款'
        
    end
end

------解决方案--------------------
SQL code
create trigger t1
on opera
for insert
as
begin
   declare @s varchar(10),@t int 
   select @s=mark from inserted
   if(@s='取款')
   begin
     if not exists(select 1 from user join inserted on user.id=inserted.id and money>change)
        rollback
    else
        update user
        set money=money-change
        from user join inserted on user.id=inserted.id 
   end
   else
        update user
        set money=money+change
        from user join inserted on user.id=inserted.id 
end