repetitive sql code blocks

  • Morning all, 

    It's kind of a "am I missing a trick" query.  Grateful for your time & advice.

    Is there a more elegant / less verbose way of coding:

    IF EXISTS
    (SELECT * FROM … <x JOIN y WHERE ….>)
    BEGIN
    (SELECT * FROM … <x JOIN y WHERE ….>)
    END

    Instead of repeating the same SELECT statement twice?

    I guess I could use dynamic SQL but then I have to worry about compilation.  I guess I could create a UDF but my SELECT doesn't seem quite complex enough to justify it?

    Thank you!

  • snomadj - Wednesday, August 22, 2018 2:59 AM

    Morning all, 

    It's kind of a "am I missing a trick" query.  Grateful for your time & advice.

    Is there a more elegant / less verbose way of coding:

    IF EXISTS
    (SELECT * FROM … <x JOIN y WHERE ….>)
    BEGIN
    (SELECT * FROM … <x JOIN y WHERE ….>)
    END

    Instead of repeating the same SELECT statement twice?

    I guess I could use dynamic SQL but then I have to worry about compilation.  I guess I could create a UDF but my SELECT doesn't seem quite complex enough to justify it?

    Thank you!

    Quick question, why do you need the IF EXIST statement? If it doesn't exist, then nothing is returned.
    😎

  • Don't run the query twice. Run it one time. SELECT whatever FROM wherever WHERE somesetofrestrictivefilteringthatusesanindexanddoesnthavecalculationsandfunctionsonit is the right way to do something like this. Trying to determine if there is data and then running a query is doing work two times. Yes, the EXISTS does bail if it finds something, but, it doesn't bail if it doesn't find anything. It has to peruse the data set. Well, just peruse the data set. As Eirikur says, if nothing is there, nothing is returned. Although, technically, there is a return. You'll get a set of column definitions where data would have been if there was any data. You'll have to deal with that in the code/report/whatever it is you're writing.

    "The credit belongs to the man who is actually in the arena, whose face is marred by dust and sweat and blood"
    - Theodore Roosevelt

    Author of:
    SQL Server Execution Plans
    SQL Server Query Performance Tuning

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply