具有所有字段名称的UNION,不存在名称的null

时间:2019-10-22 19:12:04

标签: sql sql-server

我正在摆弄这段代码,以查找具有我需要的所有字段的所有表名。

select t.name, c.name
from sys.columns c
join sys.tables t
on c.object_id = t.object_id
where c.name like '%ID%' 
     OR c.name like '%ID1%'
     OR c.name like '%ID2%'
     OR c.name like '%ID3%'
     OR c.name like '%ABC%'
     OR c.name like '%RTG%'
order by c.name

我得到了数百个表名和字段名。基本上,我正在尝试找出最简单的方法来获得如下结果:

select col1, col2, col3, null as col4 from table1
union all
select col1, col2, col3, null as col4 from table2
union all
select col1, col2, col3, col4 from table3;

这里的挑战是...我可以输入逻辑,但是我要处理数百个表/字段,并且很难对所有这些逻辑进行硬编码。我正在使用SQL Server Azure。有什么想法吗?有想法吗?有建议吗?

1 个答案:

答案 0 :(得分:2)

我不知道我是否真的推荐这样做,但是您可以使用范围界定技巧,以便所有子查询都基本相同:

select t.*
from (values (NULL, NULL, NULL, NULL)) v(a, b, c, d) cross apply
     (select a, b, c, d
      from table1
     ) t
union all
select t.*
from (values (NULL, NULL, NULL, NULL)) v(a, b, c, d) cross apply
     (select a, b, c, d
      from table2
     ) t
. . . 

基本上,子查询将从表(如果存在)中选择值。否则,它将从v获取它们。

编辑:

或者正如马丁指出:

select t.*
from (values (NULL, NULL, NULL, NULL)) v(a, b, c, d) cross apply
     ((select a, b, c, d from table1
      ) union all
      (select a, b, c, d from table2
      ) union all
      . . .
     ) t