I have a query that regularly returns "nothing", and I would like to run a different query if this is the case, but I know not of the way of doing this. If anyone could be of help please.
Here is the current code I am using...
SELECT * FROM cfg_users JOIN cfg_ash ON cfg_users.iUserId = cfg_ash.iUserid WHERE iTeamId
='0' AND sDisabled IS NULL AND iStatusId > 0 AND sDate = '2014-08-01' GROUP BY cfg_users.iUserId
ORDER BY iStatusId, sName
I basically want to say
IF <my code> IS NULL THEN <do other code>, IF <my code> IS NOT NULL THEN return the result.
Thanks
If both queries can only return a single row (or nothing), there is a simple, efficient solution without CTEs: ( SELECT column1, column2 FROM mytable WHERE <1st SET OF complex conditions> ) UNION ALL ( SELECT column1, column2 FROM mytable WHERE <2nd SET OF complex conditions> ) LIMIT 1; Related: Save this answer.
The common table expression ( WITH clause) wraps the first query that we want to execute no matter what. We then select from the first query, and use UNION ALL to combine the result with the result of the second query, which we're executing only if the first query didn't yield any results (through NOT EXISTS ).
Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed. If the condition evaluates to False, then T-SQL statements followed by ELSE keyword will be executed.
To combine two or more SELECT statements to form a single result table, use the set operators: UNION, EXCEPT or INTERSECT.
There are some simple way only use sql.
Define your first query as a temp table, with union all, filter the second query with temp table's count.
with temp as (select * from t1 where 1=0)
select * from temp
union all
select * from t2 where (select count(*) from temp) =0
This query will return the second table's records.
with temp as (select * from t1 )
select * from temp
union all
select * from t2 where (select count(*) from temp) =0
And if temp query have result, only return temp query.
You can test with sql fiddle here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With