SQL Server Query Optimization: Where (Col=@Col or @Col=Null)

前端 未结 1 1319
误落风尘
误落风尘 2021-01-20 10:13

Not sure where to start on this one -- not sure if the problem is that I\'m fooling the query optimizer, or if it\'s something intrinsic to the way indexes work when nulls a

相关标签:
1条回答
  • You have a combination of issues, most likely

    1. Parameter sniffing
    2. OR is not a good operator to use

    But without seeing the plans, these are educated guesses.

    Parameter sniffing

    ... of the default "NULL". Try it with different defaults, say -1 or no default.

    The @ID = -1 with a default of NULL and parameter sniffing = trivial check, so it's faster.

    You could also try OPTIMISE FOR UNKNOWN in SQL Server 2008

    The OR operator

    Some ideas..

    If the columns is not nullable, in most cases the optimiser ignores the condition

    st.ID = ISNULL(@ID, st.ID)
    

    Also, you can use IF statement

    IF @ID IS NULL
       SELECT ... FROM...
    ELSE
       SELECT ... FROM... WHERE st.ID
    

    Or UNION ALL in a similar fashion.

    Personally, I'd use parameter masking (always) and ISNULL in most cases (I'd try it first)

    alter procedure SomeProc
      @ID int = NULL
    AS
    declare @maskID int
    select @maskID = @ID
    ...
    
    0 讨论(0)
提交回复
热议问题