表A 
货币种类 varchar --其他数据项还有  不重要不写了 表A-B是主从表 A主表,B从表 表B 
单价 int, 总价 int --其他数据项还有  不重要不写了 表C 
货币种类 varchar , 汇率 int 表A的货币是个select BOX 就是表C的外键 c.货币种类=a.货币种类 现在是改变表A中 update 货币种类 然后让 B表中的 2个单价 都自×以表C的汇率 ; 比如 
货币种类 
人名币 单价  总价 
100  100 货币种类  汇率 
人名币    1 
美元      1/8 
欧元      1/5现在UPDATE A set  货币种类= '美元'  然后自动把 表B 变成 100/8 , 100/8 再update a set 货币种类= '欧元’ 后面的值肯定是不对的 这个触发器的中间部分应该怎么写呢? 就是 if(货币种类)  begin 这里的SQL语句怎么写 end

解决方案 »

  1.   

    create trigger tg on 表A
    for update
    as
    if update(货币种类)
    begin
      update B set b.单价 = b.单价*c.汇率,b.总价=b.总价*c.汇率 --应该是这里出的问题,你要先把汇率关系弄清楚
      from 表B B join inserted A on a.id=b.id join 表C c on a.货币种类=c.货币种类
    end
      

  2.   

    create trigger t1
    on a
    for update
    as
    begin
      declare @t float
      set @t=(select 汇率 from c,deleted s where c.货币种类=s.货币种类)/(select 汇率 from c,inserted p where c.货币种类=p.货币种类)
      update b set 单价=单价/@t,总价=总价/@t
    end
      

  3.   


    表C 
    货币种类 varchar , 汇率 int 货币种类  汇率 
    人名币    1 
    美元      1/8 
    欧元      1/5 

    如果汇率是int,就不能是1/8,1/5这种形式,要么用decimal类型,要么用字符型,建议用前一种
      

  4.   

    ---测试数据---
    if object_id('[A]') is not null drop table [A]
    go
    create table [A]([货币种类] varchar(6))
    insert [A]
    select '人名币'
    if object_id('[B]') is not null drop table [B]
    go
    create table [B]([单价] int,[总价] int)
    insert [B]
    select 100,100
    if object_id('[C]') is not null drop table [C]
    go
    create table [C]([货币种类] varchar(6),[汇率] dec(18,3))
    insert [C]
    select '人名币',1 union all
    select '美元',1.0/8 union all
    select '欧元',1.0/5
     
    create trigger tri_update
    on A
    for update
    as
    if update(货币种类)
      begin
        update B
        set 单价=单价*c.汇率, 总价=总价*c.汇率
         from inserted,C
        where inserted.货币种类=c.货币种类
      end
    --1.
    UPDATE A set  货币种类= '美元' select * from [B]
    /*
    单价          总价          
    ----------- ----------- 
    12          12(所影响的行数为 1 行)
    */--2.
    UPDATE A set  货币种类= '欧元' select * from [B]
    /*
    单价          总价          
    ----------- ----------- 
    20          20(所影响的行数为 1 行)
    */
      

  5.   

    看来总价也要用dec(18,3)才行,否则12.5变为12了