Conditional where clause

  • Hi Frank

    This becomes the "most wanted" these days... 🙂

    You can handle this by OR within your WHERE clause:

    WHERE (@incident_id NOT NULL AND incident_id = @incident_id

    OR (@res_id IS NOT NULL AND res_id = @res_id)

    OR (@unit_id IS NOT NULL AND unit_id = @unit_id)

    But

    For these kind of procedures you should use the RECOMPILE option for procedure creation to void wrong execution plans. Best performance will be reached with three procedures.

    Greets

    Flo

  • After I wrote that, I was looking at some of the other forum posts for inspiration and I'm leaning on what you said. Would likely be better to have 3 or 4 well tuned queries than 1 massive POS that's hard to debug and has questionable performance.

    While I don't anticipate much of a performance issue, I've recently reviewed some of my earlier "git-r-done" code and was thinking of taking a "do it right" approach for this project. 😀

    Thanks for the info.

    Frank

  • To add to what Flo has shown you - if this is not going to be executed a lot, then the recompile option works well. But, if it is going to be executed many times a day - then you really want to create separate procedures or use dynamic SQL.

    Jeffrey Williams
    “We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”

    ― Charles R. Swindoll

    How to post questions to get better answers faster
    Managing Transaction Logs

  • I dont anticipate it being called much since its more of a report type query, but I'm saying that today, who's knows whats going to happen 4 - 6 months down the line.

    I do know I don't really want to go down the dynamic sql path if I can help it, so right now looking at doing it "best practices" the first time so I dont have to figure it out later on if the project gets more use than anticipated.

    Thanks for the input, appreciate it a lot.

    Frank

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

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