Search code examples
t-sqljoinunion

tSQL Run queries conditionally with IF EXISTS, connect them using UNION


I may have programmed myself into a corner, and I'm hoping somebody can help.

I created a stored procedure with several queries, and I join them with UNION ALL commands:

Query 1 
UNION ALL 
Query 2 
UNION ALL
Query 3 

But now my client wants to see only certain results based on conditions. So, if something is true, show only results of query 1, something else, join query 1 and 2, and so on.

I figured out how to add the conditional logic with IF EXISTS statements, like this:

IF EXISTS (some condition)
    BEGIN
        Query 1
    END

IF EXISTS (some other condition)
    BEGIN
        Query 2
    END

and so on. This would work fine, except that now I can't use the UNION statement. sql doesn't like the UNION keyword inside the BEGIN/END block, and it doesn't work between them either.

Is there a way to use UNION in this scenario, or some other way to join these blocks together into a single output dataset? My project is really large, and breaking all this up, or doing it programmatically, would be a big headache. It would be great if I could modify my stored procedure to do this. Any help is appreaicated.


Solution

  • Sometime is simpler to gather your results incrementally than overcomplicate your where clause.

    You could declare a table variable (or a temp table) to hold your results temporarily until you're ready to return, something like:

    DECLARE @Results TABLE (myCol1 datatype, myCol2 datatype, myColn etc)
    
    IF CONDITION 1
    INSERT INTO @Results (
        myCol1, myCol2, myColn
    )
    SELECT
        myCol1, myCol2, myColn
    FROM
        myQuery
    
    /*ELSE*/ IF CONDITION 2
    INSERT INTO @Results (
        myCol1, myCol2, myColn
    )
    SELECT
        myCol1, myCol2, myColn
    FROM
        myQuery
    
    /*ELSE*/ IF CONDITION 3
    INSERT INTO @Results (
        myCol1, myCol2, myColn
    )
    SELECT
        myCol1, myCol2, myColn
    FROM
        myQuery
    
    
    -- return results
    SELECT * FROM @Results
    

    PS: you don't necessarily need to specify BEGIN/END after IF, when only one statement is intended after, however it is indeed good practice to add them for readability. Totally your choice.