T-SQL Where Clause Case Statement Optimization (optional parameters to StoredProc)

后端 未结 5 1368
灰色年华
灰色年华 2021-02-05 10:54

I\'ve been battling this one for a while now. I have a stored proc that takes in 3 parameters that are used to filter. If a specific value is passed in, I want to filter on that

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 11:34

    if you are running SQL Server 2005 or above you can use IFs to make multiple version of the query with the proper WHERE so an index can be used. Each query plan will be placed in the query cache.

    also, here is a very comprehensive article on this topic:

    Dynamic Search Conditions in T-SQL by Erland Sommarskog

    it covers all the issues and methods of trying to write queries with multiple optional search conditions

    here is the table of contents:

      Introduction
          The Case Study: Searching Orders
          The Northgale Database
       Dynamic SQL
          Introduction
          Using sp_executesql
          Using the CLR
          Using EXEC()
          When Caching Is Not Really What You Want
       Static SQL
          Introduction
          x = @x OR @x IS NULL
          Using IF statements
          Umachandar's Bag of Tricks
          Using Temp Tables
          x = @x AND @x IS NOT NULL
          Handling Complex Conditions
       Hybrid Solutions – Using both Static and Dynamic SQL
          Using Views
          Using Inline Table Functions
       Conclusion
       Feedback and Acknowledgements
       Revision History

提交回复
热议问题