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

萝らか妹 提交于 2019-12-07 19:34:41

问题


I have a table with many columns like:

Table A:

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

How can I insert into Table B like below?

Table B:

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

Thank you!


回答1:


You can also use a normal UNPIVOT for this.

A example using table variables:

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



回答2:


You need to Unpivot the data. One option uses CROSS APPLY and table valued constructor

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



回答3:


Try with dynamic 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)



回答4:


Use UNPIVOT:

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


来源:https://stackoverflow.com/questions/39763621/how-to-insert-row-into-a-table-by-select-column-name-and-value-from-another-tabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!