Sql 使用另一个表更新表,该表采用第二个表的列名称
我有一个表要用另一个表更新。问题是要更新的列名包含在结果select中 我尝试了许多不同的方法,在stackoverflow中处理了这些案例,但没有成功Sql 使用另一个表更新表,该表采用第二个表的列名称,sql,sql-server,Sql,Sql Server,我有一个表要用另一个表更新。问题是要更新的列名包含在结果select中 我尝试了许多不同的方法,在stackoverflow中处理了这些案例,但没有成功 CREATE TABLE #tableA ( TA int , FM int , YTM int , YTW int , FFH int , TCWH int , BRH int , DH int , DV int , BN int , PP int ); select * from #tableA
CREATE TABLE #tableA (
TA int
, FM int
, YTM int
, YTW int
, FFH int
, TCWH int
, BRH int
, DH int
, DV int
, BN int
, PP int
);
select * from #tableA;
CREATE TABLE #TableB (
footnote VARCHAR(20) NOT NULL
, row_ref int NOT NULL
);
INSERT INTO #TableB (footnote, row_ref)
VALUES ('TA', 1),
('FFH', 2),
('BRH', 7);
我们的想法是使用TableB中的值更新TableB中定义的TA、FFH和BRH列中的tableA,如果您希望TableB中的每一行对应tableA中的一行,那么应该这样做
INSERT INTO #tableA
(TA, FM, YTM, YTW, FFH, TCWH, BRH, DH, DV, BN, PP)
SELECT IIF(footnote = 'TA', row_ref, NULL) AS TA
, IIF(footnote = 'FM', row_ref, NULL) AS FM
, IIF(footnote = 'YTM', row_ref, NULL) AS YTM
, IIF(footnote = 'YTW', row_ref, NULL) AS YTW
, IIF(footnote = 'FFH', row_ref, NULL) AS FFH
, IIF(footnote = 'TCWH', row_ref, NULL) AS TCWH
, IIF(footnote = 'BRH', row_ref, NULL) AS BRH
, IIF(footnote = 'DH', row_ref, NULL) AS DH
, IIF(footnote = 'DV', row_ref, NULL) AS DV
, IIF(footnote = 'BN', row_ref, NULL) AS BN
, IIF(footnote = 'PP', row_ref, NULL) AS PP
FROM #TableB;
所以您希望只插入一行?
insert into #tableA ([TA],[FFH],[BRH])
select [TA],[FFH],[BRH]
from #TableB
pivot (max(row_ref) for footnote in ([TA],[FFH],[BRH])) pvt