大家好,我在练习简单的进销存流程
各个表如下:库存表B:
商品名称,数量,仓库名称
A,   10,  K1入库表C:
商品名称,数量,仓库名称
B,        10, K2
A,        5,  K1 我想实现的是:
如果 表C的商品名称,仓库名称 =表B的商品名称,仓库名称的话,
     表B的数量=表B的数量+表C的数量
如果 表C的商品名称,仓库名称 <> 表B的商品名称,仓库名称的话
     表C的记录就插入表B请问相关的语句应该怎么写?谢谢!

解决方案 »

  1.   


    --两步操作insert into b
    select * from c
    where not exists (select 1 from b where 商品名称 = b.商品名称 and 仓库名称 = b.仓库名称)update b
    set b.数量 = b.数量 + (select sum(数量) from c where 商品名称 = b.商品名称 and 仓库名称 = b.仓库名称)
      

  2.   


    --找出在库存b表不存在商品名称和仓库名称相同的记录插入表b
    insert into b
    select * from c
    where not exists (select 1 from b where 商品名称 = b.商品名称 and 仓库名称 = b.仓库名称)--更新库存b表商品名称和仓库名称相同记录的数量
    update b
    set b.数量 = b.数量 + (select sum(数量) from c where 商品名称 = b.商品名称 and 仓库名称 = b.仓库名称)
      

  3.   

    insert into
     b
    select
     * 
    from
     c
    where
     not exists (select 1 from b where 商品名称 = b.商品名称 and 仓库名称 = b.仓库名称)update
     b
    set
     b.数量 = isnull(b.数量,0) + (select sum(数量) from c where 商品名称 = b.商品名称 and 仓库名称 = b.仓库名称)
      

  4.   

    select 商品名称,仓库名称,sum(数量+数量1) as 数量
    from 
    (select isnull(b.商品名称,c.商品名称)商品名称,
            isnull(b.仓库名称,c.仓库名称)仓库名称,
            b.数量,c.数量 as 数量1
    from b full join c
    on b.商品名称=c.商品名称 and b.仓库名称=c.仓库名称) tb
    group by 商品名称,仓库名称