views:

239

answers:

2

I have a select query. I want to replace that select query with another select if that returns no rows.

For instance lets say I have:

Select * from Temp2
if (@@rowcount=0)
 select * from Temp1

At the c# end, I retrieve it as a dataset. So if no rows are returned, it would do another select. But this select would be in Tables[1] not Tables[0].

So essentially, What I want to do is to replace the first select results in the sql stored proc with that of the last if @@rowcount = 0. I am sure this can be done. I want a tidy solution.

I can do something like this:

if ((select count(ID) from Temp2) =0)
  select * from Temp1
else
  select * from Temp2

but I have 3 selects. I would like to do it with max 2 selects because my select statement is more complex than the trivial example given and I dislike repeat the same select twice (e.g. select on Temp2).

Thanks

+8  A: 
select * from Temp2
UNION ALL
select * from Temp1
where not exists (select * from Temp2)
Jeffrey Kemp
+ 1 cheers.. union all did it... since temp2 won't have temp1 values, there is no point of the last where... Thanks very much :)
waqasahmed
ok but if you remove the where, it will always return the rows form Temp1, even if there are rows in Temp2; which is different to the logic you had in your original question.
Jeffrey Kemp
I know.. my select statements have the where clause to filter the results.. and it will never return a result where a row in one select also exists as a row in another select.
waqasahmed
This will always return the records from Temp1, even if the result from Temp2 is not empty.
Guffa
@Guffa: "not exists" evaluates to false if (select * from Temp2) is not empty, so it would not in that case return any rows from Temp1.
Jeffrey Kemp
+2  A: 

Perhaps a table variable?

declare @result table({column defs})

insert @result
select (..query 1...)

if(@@rowcount = 0)
  insert @result
  select (..query 2...)

select * from @result
Marc Gravell
+1 thanks. but this is a more complex solution.. But I might need to use in future more complex stored procs, so thanks again.
waqasahmed