首页 > 解决方案 > 如果没有返回行,SQL 返回默认值

问题描述

我有一个返回结果集的 SQL 脚本,如果以下脚本没有产生任何结果,则要求返回具有默认值的默认结果集。它应该与以下脚本具有相同的列名

 -- Return final results
    SELECT  
        p.worked                                                                           [AccountsWorked],
        p.rcmade                                                                       [RPC's],
        p.obtained                                                                             [PTPCount],
        p.amount                                                                          [PTPValue], 
                                                                                                [PreviousDayPTPValue]

    FROM
        @tab_performance p JOIN
        dbo.user usr ON
            (p.usr_code = usr.usr_code) JOIN
        dbo.team tme ON 
            (tme.tme_id = usr.tme_id)   
            AND p.usr_code = @usr_code

如果没有返回行,我需要返回默认结果集。因此,所有列都应返回 NULL 或任何默认值。

我试过条件选择语句没有任何运气,我也试过@@ROWCOUNT

标签: sqlsql-servertsql

解决方案


您可以union all使用默认值向现有查询添加选择,如下所示:

<your existing query>

union all

select null accounts_worked, null right_contacts_made, null ppts_obtained .....
where not exists(
select *
from @tab_performance p JOIN
        dbo.TR_USR_User usr ON
            (p.usr_code = usr.usr_code) JOIN
        dbo.TR_TME_Team tme ON 
            (tme.tme_id = usr.tme_id)   
            AND p.usr_code = @usr_code
)

如果您不从以下内容中过滤掉任何行where,则可以进一步简化该子句:inner joins@tab_performance

<your existing query>

union all 

select null accounts_worked, null right_contacts_made, null ppts_obtained .....
where not exists(
select *
from @tab_performance
where usr_code = @usr_code
)

推荐阅读