1

I've got a SQL script which returns a result set, the requirement is to return a default result set with default values if the below script does not yield any results. It should have the same column names as the below script

 -- 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

I need to return a default result set if no rows are returned. So all the columns should be returned with NULL's or any default value.

I have tried conditional select statements without any luck, I have also tried the @@ROWCOUNT

2 Answers 2

3

You can add a union all select to your existing query with default values like this:

<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
)

The where clause could be further simplified, if your inner joins don't filter out any rows from @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
)
Sign up to request clarification or add additional context in comments.

Comments

2

I would do it with WITH and 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.