希望T-SQL执行以下操作。
我想从字段列表中返回字段名称和字段数据。
假设我有一个名为TableX的表,其中包含字段ClientID, Surname, Firstname, Age, Sex
。我只想返回ClientID, Surname and Firstname
。
我想在临时表中进行以下操作,然后再仔细检查
+-------------+--------------+------------+
| Client ID | FieldName | FieldData |
+-------------+--------------+------------+
| 1 | Surname | "Smith" |
| 1 | Firstname | "Andrew" |
+-------------+--------------+------------+
答案 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