如何为表中的每列选择不同的数据

时间:2014-12-05 08:30:21

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

具有以下查询:

declare @type int = 1

select cf.id, cf.name 
from dbo.tbl1 cf
inner join dbo.tbl2 ct on cf.id = ct.field_id and ct.[type_id] = @type

回应是:

ID   NAME
1   number
2   city
4   location
5   username

我想在响应中添加一个字段,我必须从select中获取每个名称 类似的东西:

when name = number then select number from myTbl
when name = city then select name from region_tbl
when name = location then select name from location_tbl
when name = username then select user from user_tbl

并且响应必须如下:

ID   NAME      Field
1   number     1        
2   city       Paris
4   location   some_location
5   username   admin

是否可以做这样的事情?

或者我可以在表格中添加一个列,响应将如下:

ID   NAME     command
1   number    select number from myTbl
2   city      select name from region_tbl
4   location  select name from location_tbl
5   username  select user from user_tbl

并动态执行命令,响应必须如下:

ID   NAME      command
1   number     1        
2   city       Paris
4   location   some_location
5   username   admin

1 个答案:

答案 0 :(得分:2)

您可以使用CASE WHEN THEN来获取使用子查询

所需的结果

如果每个表列的数据类型不同,则可能必须将子查询结果转换为一个统一类型,如VARCHAR

   select cf.id, cf.name 
   thirdColumn = CASE 
                  WHEN cf.name = 'number' THEN CAST((select TOP 1 number from myTbl) AS VARCHAR)
                  WHEN cf.name = 'city' THEN CAST((select TOP 1 name from region_tbl) AS VARCHAR)
                  WHEN cf.name = 'location' THEN CAST((select TOP 1 name from location_tbl) AS VARCHAR)
                  WHEN cf.name = 'username' THEN CAST((select TOP 1 user from user_tbl) AS VARCHAR)
  from dbo.tbl1 cf
  inner join dbo.tbl2 ct on cf.id = ct.field_id and ct.[type_id] = @type

注意 - 不使用TOPWHERE条件的子查询可能会导致您将多行作为返回值而导致错误。因此,调整子查询以始终返回1行。