How should i go about doing something like:
IF the following select has any rows
SELECT ID, NAME FROM TABLE WHERE ID=@ID
then return that actual select, otherwise use another select statement.
I use somwthing like
IF EXISTS(SELECT ID, NAME FROM TABLE WHERE ID=@ID)
SELECT ID, NAME FROM TABLE WHERE ID=@ID
ELSE
SELECT QTY FROM TABLE WHERE ID=@ID
but this way i use the first select twice(once in the check and once the actual return record set.
It’s not as inefficient as you think. The EXISTS keyword means that the optimiser stops after 1 record is found.
But, if you really want to avoid repetition, you can do something like…
The problem here is that you now return up to 2 record sets to the client. The first of which my be empty (but field headers, etc, are still returned – just with 0 records).
You could avoid that by inserting results into a table variable, and only returning them to the client if there are any records. But I think it would be noticeably slower than just using EXISTS() like you already do.