我有一个包含许多列的表,例如:
表A :
ColumnA | ColumnB | ColumnC | ColumnD | ColumnE _______________________________________________ valueA | valueB | valueC | valueD | valueE
我如何像下面这样插入表B?
表B :
ColumnName | ColumnValue _________________________ ColumnA | valueA ColumnB | valueB ColumnC | valueC ColumnD | valueD ColumnE | valueE
谢谢!
您也可以为此使用普通的UNPIVOT。
使用表变量的示例:
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;
返回值:
ColumnName ColumnValue ---------- ----------- ColumnA 1 ColumnB 2 ColumnC 3 ColumnD 4 ColumnE 5