使用查询结果更新表中的列

时间:2018-08-17 21:18:49

标签: sql-server

在SQL Server中,我有一个输出表EngFilterlbl,该表中填充有数据以打印出标签,除了序列号外,所有其他信息:

partnum,comments, freq_rate, labelnum, job, serial_num
-------------------------------------------------------
345                100mghz       1     4567  
345                100mghz       2     4567
345                100mgzh       3     4567

我有一个查询结果,可以从其他表中获取序列号

track_num,item,ref_num,ref_line_suf,ser_num
--------------------------------------------
 123       345    4567     0         9991
 123       345    4567     0         9992
 123       345    4567     0         9993

我需要将序列号放入EngFilterlbl中,序列号的顺序无关紧要。

查询结果的代码为

select 
    matltrack_mst.track_num,item, ref_num, ref_line_suf,  ser_num
from 
    matltrack_mst
left outer join 
    ser_track_mst on ser_track_mst.track_num = matltrack_mst.track_num 
                  and ser_track_mst.site_ref = matltrack_mst.site_ref
where 
    ref_num = @job  and ref_line_suf = @suffix

1 个答案:

答案 0 :(得分:0)

在更新语句中,可以在EngFilterlbl表和从中获取ser_num的其他表之间使用inner join。如下所示-

update eng -- this will indicate to update EngFilterlbl table
set eng.serial_num = mtm.ser_num -- I assume ser_num is part of matltrack_mst table, so used mtm alias
from EngFilterlbl eng
  inner join matltrack_mst mtm on mtm.ref_num = eng.job
  Left outer join ser_track_mst stm on stm.track_num = mtm.track_num 
                                and stm.site_ref = mtm.site_ref
where 
   ref_line_suf = @suffix