Converting columns to rows is called UNPIVOT . You did not specify which version of SQL Server you are using, but there are several ways to get the result.
You can use SELECT with UNION ALL :
SELECT name, 'age' as column, cast(age as varchar(10)) as value FROM yourtable UNION ALL SELECT name, 'gender' as column, gender as value FROM yourtable;
If you are using SQL Server 2005+, you can use the UNPIVOT function:
SELECT name, column, age FROM ( SELECT name, age = cast(age as varchar(10)), gender FROM yourtable ) d UNPIVOT ( value for column in (age, gender) ) unpiv;
Finally, instead of the UNPIVOT function, you can also use CROSS APPLY with VALUES (2008+) or UNION ALL :
SELECT name, column, age FROM yourtable CROSS APPLY ( VALUES ('age', cast(age as varchar(10)), ('gender', gender) ) c (column, value);
Any of these versions will give you the result you want. You will notice that I needed to arrange the age column in varchar . This is because the data type / length (in univot) of the columns must be the same as you convert them to a single column in the final result.
Taryn
source share