使用MSSQL中的DYNAMIC SQL从另一个表更新一个表中的值

时间:2014-07-05 11:46:07

标签: sql sql-server

我有一个临时表A有2列col1:ID col2:使用XML生成的值。我需要更新表B中对应于column1的列:表A的ID,其中值为col2:表A的值。注意:只需要更新表B中的特定列而不是全部

表A

+----+-------+
| ID | Value |
+----+-------+
|  1 |   533 |
|  5 |    34 |
|  6 |    56 |
+----+-------+

表B

+-----+---+---+---+----+----+---+
|  1  | 2 | 3 | 4 | 5  | 6  | 7 |
+-----+---+---+---+----+----+---+
| 533 |   |   |   | 34 | 56 |   |
+-----+---+---+---+----+----+---+

 declare dynsql varchar(4000) = ' update table B set....... '

2 个答案:

答案 0 :(得分:0)

INSERT INTO tb  
SELECT [1],[2],[3],[4],[5],[6],[7] FROM
(SELECT 
id,value
  from ta)as p
PIVOT
(AVG(value) FOR id IN([1],[2],[3],[4],[5],[6],[7])
 )as bah

Fiddle

答案 1 :(得分:0)

尝试以下查询:

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 '+@columns1+' 
            From ( 
                  Select '+ @columns2+'
                  From (Select Id, Value From TableA) AS p
                  Pivot (MAX(Value) For Id IN ('+@columns2+')) AS Pvt
            )z'

EXECUTE(@sql)