如何将一个表的列数据复制到另一个表,其中一个表的行数据与另一个表的列名匹配

时间:2016-02-15 07:18:03

标签: sql-server tsql

我有两张桌子:

Table 1:
Id | PersonId |Variable  | Value|
1      12      FirstName  NULL
2      12      Address    NULL
------------------------
Table2:
Id | PersonId | FirstName| LastName| Address | Phone
1      12          Tommy      Stark     NY        12365

我需要将表2中的数据复制到表1中 我需要输出如:

Table 1:
Id | PersonId |Variable  | Value|
1      12      FirstName  Tommy
2      12      Address    NY

2 个答案:

答案 0 :(得分:0)

您可以使用一系列case表达式将表1值与表2列名匹配。它很笨重,但应该有效:

UPDATE t1
SET    t1.value = CASE t1.variable 
                  WHEN 'FirstName' THEN t2.firstname 
                  ELSE t1.value
                  END,
       t1.value = CASE t1.variable
                  WHEN 'LastName' THEN t2.lastname
                  ELSE t1.value
                  END,
       t1.value = CASE t1.variable
                  WHEN 'Address' THEN t2.address
                  ELSE t1.value
                  END,
       t1.value = CASE t1.phone
                  WHEN 'Phone' THEN t2.phone
                  ELSE t1.value
                  END
FROM   t1
JOIN   t2 ON t1.personid = t2.personid

答案 1 :(得分:0)

Declare @Table1 TABLE 
    (Id int, PersonId int, Variable varchar(9), Value varchar(4))
;

INSERT INTO @Table1
    (Id, PersonId, Variable, Value)
VALUES
    (1, 12, 'FirstName', NULL),
    (2, 12, 'Address', NULL)
;

DECLARE @Table2 TABLE 
    (Id int, PersonId int, FirstName varchar(5), LastName varchar(5), Address varchar(2), Phone int)
;

INSERT INTO @Table2
    (Id, PersonId, FirstName, LastName, Address, Phone)
VALUES
    (1, 12, 'Tommy', 'Stark', 'NY', 12365)


select TT.Id,
TT.PersonId,
TT.Variable,
CASE 
    WHEN T.col = TT.Variable 
    THEN T.val 
    END value 
from @Table1 TT
INNER JOIN (
select col,val from @Table2 t CROSS APPLY (values ('Id',CAST(Id AS VARCHAR)), ('PersonId',CAST(PersonId AS VARCHAR)),
('FirstName',CAST(FirstName AS VARCHAR)),
('LastName',CAST(LastName AS VARCHAR)),
('Address',CAST(Address AS VARCHAR)),
('Phone',CAST(Phone AS VARCHAR)))cs(col,val))T
ON T.col = TT.Variable