문제

Would like an T-SQL to do the following.

I would like to return the Field name and the Field data from a list of fields.

Let say I have a table called TableX which has fields ClientID, Surname, Firstname, Age, Sex. I only want to return ClientID, Surname and Firstname.

I want the following in a temp table to then scrutinize further

+-------------+--------------+------------+
| Client ID   |  FieldName   |  FieldData |
+-------------+--------------+------------+
| 1           |  Surname     |  "Smith"   |
| 1           |  Firstname   |  "Andrew"  |
+-------------+--------------+------------+
도움이 되었습니까?

해결책

You can use union like this:

// 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

The result will be this:

ClientID    FieldName FieldData
----------- --------- --------------------
1           Firstname Andrew
1           Surname   Smith
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top