【问题标题】:Cross Apply yields nulls交叉应用产生空值
【发布时间】:2018-02-27 21:17:51
【问题描述】:

我引用 MS:

CROSS APPLY 仅返回外部表中产生 表值函数的结果集。

这意味着它不会返回具有空值的行,对吧? 但是,我的查询是:

select ....,cat_custom,....
from ...(various inner joins)...                
cross apply
                (
                    select  
                        case 
                            when i.cat1='01' then 1
                            when i.cat2='04' then 2
                            when i.cat2='07' then 3
                            when i.cat2 in ('08') or i.cat3 in ('014','847') then 4
                            else null 
                        end as cat_custom
                ) as cat_custom_query

...果然,我得到了带有空值的行。那不是OUTER apply的工作吗?怎么回事?

【问题讨论】:

    标签: sql-server tsql cross-apply


    【解决方案1】:

    CROSS APPLY 仅返回外部表中产生 表值函数的结果集。

    在您的示例中,生成了一行 - 行,它返回一个 NULL 值。

    你可以试试这个:

    select ....,cat_custom,....
    from ...(various inner joins)...                
    cross apply
                    (
                        select  
                            case 
                                when i.cat1='01' then 1
                                when i.cat2='04' then 2
                                when i.cat2='07' then 3
                                when i.cat2 in ('08') or i.cat3 in ('014','847') then 4
                                else null 
                            end as cat_custom
                        WHERE i.cat1 IN ('01', '04', '07', '08', '014', '847')
                    ) as cat_custom_query
    

    另外,如果这是您实际查询的一部分,您可以在SELECT 语句中添加结果列。您不需要在这里使用CROSS APPLY,因为您没有引用任何 SQL 对象(表、视图、函数等)。

    【讨论】:

    • 我目前在查询后放置了 where cat_custom is not null ,所以我就这样保留它,但至少现在我知道会发生什么。一个重要的细节!感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    相关资源
    最近更新 更多