Avoiding IF/ELSE

  • --I believe the DDL and my commented out notes and questions should explain what I am hoping to achieve

    CREATE TABLE #Companies (CompanyID int)

    INSERT INTO #Companies (CompanyID) VALUES (1)

    INSERT INTO #Companies (CompanyID) VALUES (2)

    INSERT INTO #Companies (CompanyID) VALUES (3)

    CREATE TABLE #CompanyGroups (CompanyGroupID char(1), CompanyID int)

    INSERT INTO #CompanyGroups (CompanyGroupID,CompanyID) VALUES ('A',1)

    INSERT INTO #CompanyGroups (CompanyGroupID,CompanyID) VALUES ('A',2)

    DECLARE @CompanyID int

    DECLARE @CompanyGroupID char(1)

    --Scenario 1

    --@CompanyID is populated, CompanyGroupID is NULL

    SET @CompanyID = 1

    SET @CompanyGroupID = NULL

    IF @CompanyID IS NOT NULL

    BEGIN

    SELECT * FROM #Companies WHERE CompanyID = @CompanyID

    END

    --Scenario 2

    --@CompanyID is NULL, CompanyGroupID is populated

    SET @CompanyID = NULL

    SET @CompanyGroupID = 'A'

    IF @CompanyID IS NULL

    BEGIN

    SELECT * FROM #Companies WHERE CompanyID IN(Select CompanyID FROM #CompanyGroups WHERE CompanyGroupID = @CompanyGroupID)

    END

    --So then I can do if else

    IF @CompanyID IS NOT NULL

    BEGIN

    SELECT * FROM #Companies WHERE CompanyID = @CompanyID

    END

    ELSE

    BEGIN

    SELECT * FROM #Companies WHERE CompanyID IN(Select CompanyID FROM #CompanyGroups WHERE CompanyGroupID = @CompanyGroupID)

    END

    --SELECT * FROM #Companies

    --SELECT * FROM #CompanyGroups

    DROP TABLE #Companies

    DROP TABLE #CompanyGroups

    --The question: My select statement is complicated and I'd prefer not to duplicate it in each part of the if/else statement.

    --Can I build a single SELECT statement that will determine if @CompanyID IS NOT NULL and select the appropriate records??

  • It's a bit ugly ... but you could do something like

    ;with companyNotNull as (

    SELECT * FROM #Companies WHERE CompanyID = @CompanyID

    ),

    companyNull as (

    Select CompanyID FROM #CompanyGroups WHERE CompanyGroupID = @CompanyGroupID

    )

    SELECT *

    FROM companyNotNull

    WHERE @companyID is not null

    UNION ALL

    SELECT *

    FROM companyNull

    WHERE @companyID is null

    Of course this replicates the if ... then ... else structure. If both values are set then the companyID takes precedence.

  • In addition to MickyT's suggestion, you could do a catch all query or the dynamic SQL method suggested in this article by Gail Shaw:

    http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

    Watch out for SQL injection if the parameter values come from the UI if you use the dynamic SQL method though.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • PLS TRY BELOW CODE

    CREATE TABLE #Companies (CompanyID int)

    INSERT INTO #Companies (CompanyID) VALUES (1)

    INSERT INTO #Companies (CompanyID) VALUES (2)

    INSERT INTO #Companies (CompanyID) VALUES (3)

    CREATE TABLE #CompanyGroups (CompanyGroupID char(1), CompanyID int)

    INSERT INTO #CompanyGroups (CompanyGroupID,CompanyID) VALUES ('A',1)

    INSERT INTO #CompanyGroups (CompanyGroupID,CompanyID) VALUES ('A',2)

    DECLARE @CompanyID int

    DECLARE @CompanyGroupID char(1)

    --SET @CompanyID = 1

    --SET @CompanyGroupID = NULL

    SET @CompanyID = NULL

    SET @CompanyGroupID = 'A'

    SELECT * FROM #Companies WHERE CompanyID = (CASE WHEN @CompanyID IS NULL THEN CompanyID ELSE @CompanyID END)

    AND CompanyID IN(Select CompanyID FROM #CompanyGroups WHERE CompanyGroupID = CASE WHEN @CompanyGroupID IS NULL THEN CompanyGroupID ELSE @CompanyGroupID END)

  • mickyT (11/15/2012)


    It's a bit ugly ... but you could do something like

    ;with companyNotNull as (

    SELECT * FROM #Companies WHERE CompanyID = @CompanyID

    ),

    companyNull as (

    Select CompanyID FROM #CompanyGroups WHERE CompanyGroupID = @CompanyGroupID

    )

    SELECT *

    FROM companyNotNull

    WHERE @companyID is not null

    UNION ALL

    SELECT *

    FROM companyNull

    WHERE @companyID is null

    Of course this replicates the if ... then ... else structure. If both values are set then the companyID takes precedence.

    It occurred to me on lookback that this is going to fail if #Companies has more than one column or that column has a data type that is incompatible with CompanyID from #CompanyGroups.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • I think this is the "normal" catch all query form for this.

    SELECT *

    FROM #Companies

    WHERE (@CompanyID IS NULL OR CompanyID = @CompanyID) AND

    (@CompanyGroupID IS NULL OR

    CompanyID IN(Select CompanyID FROM #CompanyGroups WHERE CompanyGroupID = @CompanyGroupID))


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • Additional questions. What results should be for this?

    CREATE TABLE #Companies (CompanyID int)

    INSERT INTO #Companies (CompanyID) VALUES (1)

    INSERT INTO #Companies (CompanyID) VALUES (2)

    INSERT INTO #Companies (CompanyID) VALUES (3)

    CREATE TABLE #CompanyGroups (CompanyGroupID char(1), CompanyID int)

    INSERT INTO #CompanyGroups (CompanyGroupID,CompanyID) VALUES ('A',1)

    INSERT INTO #CompanyGroups (CompanyGroupID,CompanyID) VALUES ('A',2)

    a.

    SET @CompanyID = 1

    SET @CompanyGroupID = 'A'

    b.

    SET @CompanyID = 1

    SET @CompanyGroupID = 'B'

    c.

    SET @CompanyID = 3

    SET @CompanyGroupID = 'A'

    d.

    SET @CompanyID = 3

    SET @CompanyGroupID = 'E'

    e.

    SET @CompanyID = NULL

    SET @CompanyGroupID = NULL

    :unsure:

  • You could think about something like this:

    SELECT Comp.*

    FROM #Companies AS Comp

    LEFT JOIN #CompanyGroups AS Gr ON Comp.CompanyID = Gr.CompanyID

    WHERE Comp.CompanyID = @CompanyID

    OR GR.CompanyGroupID = @CompanyGroupID

  • SELECT *

    FROM

    #Companies

    WHERE CompanyID = @CompanyID

    OR

    (

    CompanyID IS NULL AND

    CompanyID IN(Select CompanyID FROM #CompanyGroups WHERE CompanyGroupID = @CompanyGroupID)

    )

  • >>Additional questions. What results should be for this?

    The parameters will be validated through an user interface so I don't expect any of those conditions to exist.

  • Thanks all. I went with dwain.c's "normal" catch all query form.

  • dwain.c (11/15/2012)


    It occurred to me on lookback that this is going to fail if #Companies has more than one column or that column has a data type that is incompatible with CompanyID from #CompanyGroups.

    Oops ... that's what I get for rushing things probably should have done the following, which was what I had in my head at the time;with companyNotNull as (

    SELECT * FROM #Companies WHERE CompanyID = @CompanyID

    ),

    companyNull as (

    Select CompanyID FROM #CompanyGroups WHERE CompanyGroupID = @CompanyGroupID

    )

    SELECT *

    FROM companyNotNull

    WHERE @companyID is not null

    UNION ALL

    SELECT *

    FROM #Companies c

    WHERE exists (SELECT 1 FROM companyNull n WHERE n.CompanyID = c.CompanyID)

  • Post deleted. Coffee has not yet arrived.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • CELKO (11/19/2012)


    ... Companies are identified by a DUNS (we even get radio ads for DUNS here in Austin!);

    ...

    That is real delight! How cool it is! There is only one small problem here...

    Are you sure that most of people on this planet have any idea about where Austin is?

    I honestly believe, if everyone would knew that there is a radio ads for DUNS in your place, all of people would try to get to Austin to hear it straight away (may be youtube link at least)!

    I can also believe that you have checked every single company in Austin and made sure they have their DUNS done. Including every independent pizza or burger shop...

    Sorry to upset you, but unfortunately the rest of the world is not quite in Austin yet, therefore there are still some companies around (and people) who never heard about such a beautiful thing as DUNS, which allows to uniquely identify company on our small planet. Actually, I've worked for quite few large companies who do deal with a lot of corporate clients of any size, and I never, really NEVER! have seen any database where DUNS is used as PK. Actually, before you have mentioned it couple month ago, I have never even heard this word at all. But, of course, it is poor me, living on the outskirts of the world in the middle-of-no-where called London-village...

    Oh lucky you...

    I will now sleep and dream about real paradise on the earth called Austin, where even radio informs happy citizens about DUNS...

    :hehe:

    By the way, for many of us rows and records are the same... I'm so sorry... 😉

    And to OP, just stick with INT CompanyId's PKs, it's a common sense to use it... until you are from Austin where even radio...

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]

Viewing 14 posts - 1 through 13 (of 13 total)

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