表1
编号          数量    地址  产品
----------------------------------------
111206006                 
111206006             
111206006
111206006
111206006
111206006
111207022
111207022
111207022
111207022
111207022
表2
编号         数量     地址   产品
111206006    3        345    ps01
111206006    6        345    ps02
111206006    7        353    ps01
111207022    7        333    ps01
111207022    7        323    ps01
111207024    2        333    ps01
111207024    6        323    ps03
111207024    9        333    ps06
111207024    21       323    ps09结果
编号         数量     地址   产品
111206006    3        345    ps01
111206006    6        345    ps02
111206006    7        353    ps01
111206006
111206006
111206006
111207022    7        333    ps01
111207022    7        323    ps01
111207022
111207022
111207022
需求,把表2相对应的记录更新到表1中,同时表1记录行数不变,得出结果如最后一个表,

解决方案 »

  1.   


    create table 表1
    (编号 varchar(15), 数量 varchar(5), 地址 varchar(5), 产品 varchar(6))insert into 表1(编号)
    select '111206006' union all
    select '111206006' union all
    select '111206006' union all
    select '111206006' union all
    select '111206006' union all
    select '111206006' union all
    select '111207022' union all
    select '111207022' union all
    select '111207022' union all
    select '111207022' union all
    select '111207022'create table 表2
    (编号 varchar(15), 数量 varchar(5), 地址 varchar(5), 产品 varchar(6))insert into 表2
    select '111206006', '3', '345', 'ps01' union all
    select '111206006', '6', '345', 'ps02' union all
    select '111206006', '7', '353', 'ps01' union all
    select '111207022', '7', '333', 'ps01' union all
    select '111207022', '7', '323', 'ps01' union all
    select '111207024', '2', '333', 'ps01' union all
    select '111207024', '6', '323', 'ps03' union all
    select '111207024', '9', '333', 'ps06' union all
    select '111207024', '21', '323', 'ps09'
    update t1
    set t1.数量=isnull(t2.数量,''),
        t1.地址=isnull(t2.地址,''),
        t1.产品=isnull(t2.产品,'')
    from 
    (select row_number() over(partition by 编号 order by getdate()) rn, 
    编号,数量,地址,产品 from 表1) t1
    left join 
    (select row_number() over(partition by 编号 order by getdate()) rn, 
    编号,数量,地址,产品 from 表2) t2 on t1.编号=t2.编号 and t1.rn=t2.rnselect * from 表1/*
    编号              数量    地址    产品
    --------------- ----- ----- ------
    111206006       3     345   ps01
    111206006       6     345   ps02
    111206006       7     353   ps01
    111206006                   
    111206006                   
    111206006                   
    111207022       7     333   ps01
    111207022       7     323   ps01
    111207022                   
    111207022                   
    111207022                   (11 row(s) affected)
    */
      

  2.   

    很显然是个左连接  left join
      如有设  表一  table1   表二  table2 select * from table1 left jojn table2  on  table1.编号 = table2.编号  这就OK了 你试试