我有一个返回结果集的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
答案 0 :(得分:2)
您可以使用以下默认值向现有查询中添加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
)
答案 1 :(得分:0)
我会使用 WITH 和 UNION ALL
Drop table if exists #test
create table #test (
Column1 int null,
Column2 varchar(50) null
);
--INSERT INTO [#test] (Column1,Column2)
--VALUES
-- (1, 'test'),
-- (2,'test2'),
-- (3,'test3');
WITH qry AS (
select Column1, Column2 from #test
)
select * from qry
UNION ALL
select NULL as Colum1, null as Column2 where (select COUNT(*) from qry) = 0