SQL Union如果为null,则返回“空白”记录

时间:2015-01-22 19:43:12

标签: sql-server

我在excel中有一个列表,我试图填充数据库中的数据。我需要按照查询中列出的顺序提取数据,因此我使用UNION ALL来执行此操作。

但是,union" ed选项中的某些记录是空的,因此结果集中的行号变得混乱。对不起,查询有点复杂,我不能使它更简单

select * from (select top 1 fundid as fundid, fundname, effectivedate from fundnamehist where fundID = '83' order by effectivedate desc) as tbl2
union all select * from (select top 1 fundid as fundid, fundname, effectivedate from fundnamehist where fundID = '173' order by effectivedate desc) as tbl3

... --a few hundred lines like the one above, generated in excel

因此,在此示例中,如果FundID 173的内部选择结果返回 没有结果,我只会得到一个而不是两个结果。相反,我希望它返回某些内容,就像0, "", 1900-1-1之类的行而不是任何内容。我的总查询比我想要的短约400行。

我该怎么做?

我尝试在"内部"中添加ISNULL() s。选择和"外部"选择,但那不起作用。

"内"选择ISNULL s

select * from (select top 1 isnull(fundid,0) as fundid, isnull(fundname,'') as fundname, isnull(effectivedate, '1900-1-1') as effectivedate from fundnamehist where fundID = '83' order by effectivedate desc) as tbl2

"外"选择ISNULL s

select isnull(fundid,0) as fundid, isnull(fundname,'') as fundname, isnull(effectivedate, '1900-1-1') as effectivedate from (select top 1 fundid, fundname, effectivedate from fundnamehist where fundID = '83' order by effectivedate desc) as tbl2

(请注意,这是一次性过程,我并不是真的在寻找任何类型的优化)

1 个答案:

答案 0 :(得分:0)

从这个答案中找到答案:https://dba.stackexchange.com/a/41068/35665

有点乏味,但我不得不在子查询中做另一个UNION ALL

...
union all 
    select  fundid, fundname, effectivedate from 
        (select top 1 fundid, fundname, effectivedate from fundnamehist where fundID = '173' order by effectivedate desc 
            union all select null,null,'1900-1-1' 
            where not exists 
            (select top 1 fundid as fundid, fundname, effectivedate from fundnamehist where fundID = '173')
        ) as tbl3