0

I have a piece of code like this:

IF  EXISTS(SELECT VALUE
                FROM   tableA
                WHERE  nameid = 'thisName')
BEGIN   
    SELECT distinct VALUE
    FROM   tableA
    WHERE  nameid = 'thisName'
    ORDER BY value
END

ELSE BEGIN     
    SELECT distinct VALUE
    FROM   tableB
    WHERE  nameid = 'thisName'
    ORDER BY value
END

Basically select something from tableA, if I don't find result there, try it in tableB.

Is there a more efficient way how to write this? So I don't have to write select from tableA twice (once inside the EXISTS statement and once as the actual select).

I was toying with COALESCE, but it allows only one result, not a set.

Zikato
  • 536
  • 9
  • 18

1 Answers1

1

Give this a try

    SELECT distinct VALUE
    FROM   tableA
    WHERE  nameid = 'thisName'
    ORDER BY value
if(@@ROWCOUNT = 0)
BEGIN 
    SELECT distinct VALUE
    FROM   tableB
    WHERE  nameid = 'thisName'
    ORDER BY value
END
paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • The problem with this one is that it returns two selects if the first one is empty. Because I have this in stored procedure and expect only one result, it would cause troubles. – Zikato Jan 14 '16 at 06:44
  • I didn't want to be ungrateful, standalone it would be fine, but it won't work for my stored procedure. – Zikato Jan 14 '16 at 11:13