如何通过 select 列名称和 SQL 服务器中另一个 table 的值将行插入 table

How to insert row into a table by select column name and value from another table in SQL Server

我有一个包含许多列的 table,例如:

Table一个:

ColumnA | ColumnB | ColumnC | ColumnD | ColumnE
_______________________________________________
valueA  | valueB  | valueC  | valueD  | valueE

如何像下面那样插入 Table B?

Table B:

ColumnName  | ColumnValue
_________________________
ColumnA     | valueA
ColumnB     | valueB
ColumnC     | valueC
ColumnD     | valueD
ColumnE     | valueE

谢谢!

您需要Unpivot数据。一个选项使用 CROSS APPLYtable valued constructor

SELECT ColumnName,
       ColumnValue
FROM   Yourtable
       CROSS APPLY (VALUES ('ColumnA',ColumnA),
                           ('ColumnB',ColumnB),
                           ('ColumnC',ColumnC),
                           ('ColumnD',ColumnD),
                           ('ColumnE',ColumnE))TC(ColumnName, ColumnValue) 

尝试使用动态 UNPIVOT:

DECLARE @COLS VARCHAR(MAX) = ''
SELECT @COLS = @COLS + ', [' + COLUMN_NAME + ']' FROM [yourDBName].INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableA'

DECLARE @ColumNames VARCHAR(MAX)= STUFF(@COLS, 1,1, '')

DECLARE @Cmd VARCHAR(MAX) = '
SELECT * FROM
(SELECT * FROM TableA) x
UNPIVOT
(
    [Value] FOR [Column] IN (' + @ColumNames + ')
) UNPVT'

INSERT INTO TableB
EXEC (@Cmd)

使用UNPIVOT:

SELECT U.ColumnName,U.ColumnValue
FROM @tblA A
UNPIVOT
(
  ColumnValue
  for ColumnName in ([ColumnA], [ColumnB], [ColumnC],[ColumnD],[ColumnE])
) U;

您也可以为此使用普通的 UNPIVOT。

使用 table 变量的示例:

declare @TableA table (Id int identity(1,1), ColumnA int, ColumnB int, ColumnC int, ColumnD int, ColumnE int);
declare @TableB table (ColumnName varchar(30), ColumnValue int);

insert into @TableA (ColumnA, ColumnB, ColumnC, ColumnD, ColumnE) values 
(1,2,3,4,5);

insert into @TableB (ColumnName, ColumnValue)
select ColumnName, ColumnValue from @TableA
unpivot (ColumnValue for ColumnName in (ColumnA, ColumnB, ColumnC, ColumnD, ColumnE)) unpiv;

select * from @TableB;

Returns:

ColumnName  ColumnValue
----------  -----------
ColumnA     1
ColumnB     2
ColumnC     3
ColumnD     4
ColumnE     5