kneidels kneidels - 2 months ago 7
SQL Question

SQL: Querying column name using value of other field

I have the following 3 fields in the same table:

cell | home | primary
----------------------------------------------
111 2222 cell
456565 4654564 home


I would like to reach the value of either
cell
or
home
based on the value of the
primary
field.

I tried the following, which obviously does not work... but can't figure out how to convert the value of
primary
to be understood as a column name:

SELECT
(SELECT primary FROM tblstudents WHERE studentid = 39358)
FROM
tblstudents WHERE studentid = 39358


Thanks

Answer

You can use CASE:

SELECT
CASE primary WHEN 'cell' THEN cell ELSE home END AS ContactNo,
primary
FROM TableName
Comments