Sql 2008 R2 - 选择字段名称和字段值

时间:2014-03-05 15:19:24

标签: sql tsql sql-server-2008-r2 entity-attribute-value

希望T-SQL执行以下操作。

我想从字段列表中返回字段名称和字段数据。

假设我有一个名为TableX的表,其中包含字段ClientID, Surname, Firstname, Age, Sex。我只想返回ClientID, Surname and Firstname

我想在临时表中进行以下操作,然后再仔细检查

+-------------+--------------+------------+
| Client ID   |  FieldName   |  FieldData |
+-------------+--------------+------------+
| 1           |  Surname     |  "Smith"   |
| 1           |  Firstname   |  "Andrew"  |
+-------------+--------------+------------+

1 个答案:

答案 0 :(得分:0)

您可以像这样使用union

// drop the temp table if it exists
drop table #temptable

// use select...into to create a temporary table
select * into #temptable from
(
    select ClientID, 'Surname' as FieldName,  surname as FieldData from YourTable
    union all
    select ClientID, 'Firstname' as FieldName,  firstname as FieldData from YourTable
) s

// display the results...
select * from #temptable

结果将是:

ClientID    FieldName FieldData
----------- --------- --------------------
1           Firstname Andrew
1           Surname   Smith