嘗試以下查詢:
UPDATE TableB
SET [1] = ISNULL(z.[1],TableB.[1]),
[2] = ISNULL(z.[2],TableB.[2]),
[3] = ISNULL(z.[3],TableB.[3]),
[4] = ISNULL(z.[4],TableB.[4]),
[5] = ISNULL(z.[5],TableB.[5]),
[6] = ISNULL(z.[6],TableB.[6]),
[7] = ISNULL(z.[7],TableB.[7])
FROM (
SELECT [1],[2],[3],[4],[5],[6],[7]
FROM (SELECT Id, Value
FROM TableA)AS p
PIVOT (MAX(Value) FOR Id IN([1],[2],[3],[4],[5],[6],[7]))AS pvt
)z
編輯
爲了擁有動態樞使用下面的查詢:
DECLARE @columns1 NVARCHAR(1000) = '',
@columns2 NVARCHAR(1000) = '',
@sql NVARCHAR(MAX)
SELECT @Columns1 = STUFF((SELECT ',['+Value+'] = ISNULL(z.['+Value+'],TableB.['+Value+'])'
FROM (SELECT DISTINCT Value FROM TableA)z
FOR XML PATH('')),1,1,''),
@Columns2 = STUFF((SELECT ',['+Value+']'
FROM (SELECT DISTINCT Value FROM TableA)z
FOR XML PATH('')),1,1,'')
SET @sql = 'Update TableB
Set '[email protected]+'
From (
Select '+ @columns2+'
From (Select Id, Value From TableA) AS p
Pivot (MAX(Value) For Id IN ('[email protected]+')) AS Pvt
)z'
EXECUTE(@sql)
爲什麼你需要動態SQL?表B只包含一行嗎?如果不是,你怎麼知道要更新哪一行? –
與@Martin Smith所說的類似,表A只包含一組值嗎?如果不是,你怎麼知道表A的哪組值更新[表B的哪一行]? –
Martin,表B總是包含一行約140列,其中只有名稱與表A中的ID匹配的列需要更新。 – user3758593