如何根据sql server中的列值在select查询中获取列名

时间:2017-10-12 11:10:47

标签: sql sql-server sql-server-2008

表1: -

ID  NAME    ADDRESS
1   TEST1    qwr
2   TEST2    sdf

我想根据ID列值

在select查询中获取列名

EX: -

如果Id = 1,我想在select查询中选择“name”列 如果id = 2,我想在选择查询中使用“地址”列

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

我希望我清楚地传达了我的疑问。

2 个答案:

答案 0 :(得分:2)

此查询将在单列和多行中返回结果:

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

答案 1 :(得分:0)

您可以使用子查询来获得两个结果:

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