如何通过从SQL Server中的另一个表中选择列名和值将行插入到表中

时间:2016-09-29 07:06:48

标签: sql sql-server columnname

我有一个包含许多列的表格,如:

表A

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

如何在表B中插入如下?

表B

{{1}}

谢谢!

4 个答案:

答案 0 :(得分:3)

您需要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) 

答案 1 :(得分:1)

尝试使用动态UNPIVOT:

class TextInput2 extends Component {
  constructor(props) {
    super(props);
    this.state = { placeholder: props.value.length == 0 }
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(ev) {
    this.setState({ placeholder: ev.nativeEvent.text.length == 0 }); 
    this.props.onChange && this.props.onChange(ev); 
  }
  render() {
    const { placeholderStyle, style, onChange, ...rest } = this.props;

    return <TextInput 
      {...rest} 
      onChange={this.handleChange}
      style={this.state.placeholder ? [style, placeholderStyle] : style}
      />
  }
}

答案 2 :(得分:1)

你也可以使用普通的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

答案 3 :(得分:0)

使用 UNPIVOT

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