mercredi 13 janvier 2016

If select exists, use it. If not, try it on different table

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.

Aucun commentaire:

Enregistrer un commentaire