Jeswanth
Jeswanth

Reputation: 197

How to get column name in select query based on column value in sql server

Table1:-

ID  NAME    ADDRESS
1   TEST1    qwr
2   TEST2    sdf

I wanted to get column name in the select query based on ID column value

EX:-

If the Id=1 i want "name" column in select query if id=2 i want "address" column in select query

select name from table (when id=1)
select address from table(when id=2)

I hope i conveyed my query clearly.

Upvotes: 1

Views: 608

Answers (2)

mendosi
mendosi

Reputation: 2051

This query will return the results in a single column and multiple rows:

SELECT CASE WHEN id = 1 THEN name WHEN id = 2 THEN address END AS result 
  FROM table;

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1271131

You can use subqueries to get the two results:

select (select name from table where id = 1) as name,
       (select address from table where id = 2) as address;

Upvotes: 0

Related Questions