根据来自SQL Server中其他表的值更新多个列

时间:2019-04-29 05:27:14

标签: sql sql-server

我需要基于“引用”表中的值更新“主”表中的多个列。 例如,在给定的示例数据中,根据联接条件(main.ID_1 = ref),对于第一个记录(ID_1 = 10,ID_2 = 100),@ MAIN_TABLE应该更新为ABC_VAL = 11111,KLM_VAL = 33333,XYZ_VAL = 22222。 .ID_1和main.ID_2 = ref.ID_2),以及字段ref.FLD_NAME的值。也就是说,如果ref.FLD_NAME ='ABC',则main.ABC_VAL应该用相应的ref.FLD_VAL更新。

DECLARE @MAIN_TABLE TABLE ([ID_1] INT, [ID_2] INT, [ABC_VAL] INT, [KLM_VAL] INT, [XYZ_VAL] INT) 
insert @MAIN_TABLE values
(10,100,NULL,NULL,NULL),
(10,200,NULL,NULL,NULL),
(30,300,NULL,NULL,NULL)


DECLARE @REF_TABLE TABLE ([ID_1] INT, [ID_2] INT, [FLD_NAME] varchar(3),[FLD_VAL] INT) 
insert @REF_TABLE values
(10,100,'ABC',11111),
(10,100,'XYZ',22222),
(10,100,'KLM',33333),
(20,200,'ABC',88888),
(30,300,'KLM',55555)

3 个答案:

答案 0 :(得分:0)

您可以使用update join来使用case when expression

update m set ABC_VAL = abc, XYZ_VAL = xyz, KLM_VAL = klm
from @MAIN_TABLE m
join
(
  select id_1, id_2, min(case when fld_name = 'ABC' then fld_val end) as abc,
    min(case when fld_name = 'XYZ' then fld_val end) as xyz,
    min(case when fld_name = 'KLM' then fld_val end) as klm,
  from @REF_TABLE
  group by id_1, id_2, fld_name
) A on m.id_1 = a.id_1 and m.id_2 = a.id_2

答案 1 :(得分:0)

您可以使用以下脚本将列更新为所需的结果-

0 1 0
0 0 1

答案 2 :(得分:0)

您可以使用PIVOT表进行处理。

UPDATE MN
SET MN.[ABC_VAL] = REF.ABC,
    MN.[KLM_VAL] = REF.KLM,
    MN.[XYZ_VAL] = REF.XYZ
FROM @MAIN_TABLE MN 
INNER JOIN 
(
SELECT * 
FROM @REF_TABLE
PIVOT 
(MIN([FLD_VAL])  FOR [FLD_NAME] IN ([ABC],[XYZ],[KLM])
)AS PIVOTTABLE)REF ON MN.[ID_1] = REF.[ID_1] AND MN.[ID_2] = REF.[ID_2]

select * from @MAIN_TABLE