IF statements and UNIONS

  • I was wondering if someone out there knew what i am doing wrong in my SQL. Basically want i want to do is if a variable is true, union the table, if not skip it. This is a simplified version of stored procedure that I'm working on:

    DECLARE var1 BIT

    DECLARE var2 BIT

    DECLARE var3 BIT

    SET var1 = 1

    SET var2 = 0

    SET var3 = 1

    IF var1 = 1

    BEGIN

    SELECT A, B, C

    FROM table1

    END

    UNION

    IF var2 = 1

    BEGIN

    SELECT A, B, C

    FROM table2

    END

    UNION

    IF var3 = 1

    BEGIN

    SELECT A, B, C

    FROM table3

    END

  • "IF" doesn't work that way. "Where" does.

    SELECT A, B, C

    FROM table1

    where var1 = 1

    UNION

    SELECT A, B, C

    FROM table2

    where var2 = 1

    UNION

    SELECT A, B, C

    FROM table3

    where var3 = 1

    Edit: The declare and set statements are the same, I just didn't include them. And I'm assuming your actual query has correct variable names (with @ on them).

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon

  • oh duh, i should know that. Thanks for the help. I've been reading some of your other posts. You give out some good advice 😉

  • You're welcome, and thank you for the kind words.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon

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

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