2014-03-05 44 views
0

希望T-SQL执行以下操作。Sql 2008 R2 - 选择字段名称和字段值

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

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

我想在一个临时表中的以下内容,然后端详进一步

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

欢迎到StackOverflow。当您卡住时,我们会提供帮助。请努力尝试自己尝试。一旦你做出了这个努力,我们可以帮助你。 – Kermit

+0

http://technet.microsoft.com/en-us/library/ms188029.aspx –

+0

今天早上八点半以后,我已经度过了一段时间! – Spectrum

回答

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 
+0

如果您知道该联合的两个部分都返回不同的行,则最好使用UNION ALL来避免UNION所执行的隐式DISTINCT。 – thepirat000

+0

@ thepirat000是的,的确如此。我会更新我的帖子。谢谢你提醒我。 – jpw

+0

@jpw:谢谢你。我已经为此挣扎了两天了!我将如何将这变成一个动态的方面。我有一个我希望返回的FieldName的列表('姓氏','名字','年龄')这个列表是由一个select语句构建的。可能选择?谢谢。 – Spectrum