SQL Server Query: Fast with Literal but Slow with Variable

前端 未结 8 1790
清歌不尽
清歌不尽 2020-11-28 07:18

I have a view that returns 2 ints from a table using a CTE. If I query the view like this it runs in less than a second

SELECT * FROM view1 WHERE ID = 1


        
相关标签:
8条回答
  • 2020-11-28 07:48

    Came across this same issue myself and it turned out to be a missing index involving a (left) join on the result of a subquery.

    select *
    from foo A
    left outer join (
      select x, count(*)
      from bar
      group by x
    ) B on A.x = B.x
    

    Added an index named bar_x for bar.x

    0 讨论(0)
  • 2020-11-28 07:49

    I ran into this problem myself with a view that ran < 10ms with a direct assignment (WHERE UtilAcctId=12345), but took over 100 times as long with a variable assignment (WHERE UtilAcctId = @UtilAcctId).
    The execution-plan for the latter was no different than if I had run the view on the entire table.

    My solution didn't require tons of indexes, optimizer-hints, or a long-statistics-update.

    Instead I converted the view into a User-Table-Function where the parameter was the value needed on the WHERE clause. In fact this WHERE clause was nested 3 queries deep and it still worked and it was back to the < 10ms speed.

    Eventually I changed the parameter to be a TYPE that is a table of UtilAcctIds (int). Then I can limit the WHERE clause to a list from the table. WHERE UtilAcctId = [parameter-List].UtilAcctId. This works even better. I think the user-table-functions are pre-compiled.

    0 讨论(0)
  • 2020-11-28 07:51

    You could add an OPTIMIZE FOR hint to your query, e.g.

    DECLARE @id INT = 1
    SELECT * FROM View1 WHERE ID = @id OPTION (OPTIMIZE FOR (@ID = 1))
    
    0 讨论(0)
  • 2020-11-28 07:52

    Probably it is because in the parameter case, the optimizer cannot know that the value is not null, so it needs to create a plan that returns correct results even when it is. If you have SQL Server 2008 SP1 you can try adding OPTION(RECOMPILE) to the query.

    0 讨论(0)
  • 2020-11-28 07:53

    I know this is long since answered, but I came across this same issue and have a fairly simple solution that doesn't require hints, statistics-updates, additional indexes, forcing plans etc.

    Based on the comment above that "the optimizer cannot know that the value is not null", I decided to move the values from a variable into a table:

    Original Code:

    declare @StartTime datetime2(0) = '10/23/2020 00:00:00'
    declare @EndTime datetime2(0) = '10/23/2020 01:00:00'
        
    SELECT * FROM ...
    WHERE 
    C.CreateDtTm >= @StartTime
    AND  C.CreateDtTm < @EndTime
    

    New Code:

    declare @StartTime datetime2(0) = '10/23/2020 00:00:00'
    declare @EndTime datetime2(0) = '10/23/2020 01:00:00'
    
    CREATE TABLE #Times (StartTime datetime2(0) NOT NULL, EndTime datetime2(0) NOT NULL)
    INSERT INTO #Times(StartTime, EndTime) VALUES(@StartTime, @EndTime)
    
    SELECT * FROM ...
    WHERE 
    C.CreateDtTm >= (SELECT MAX(StartTime) FROM #Times)
    AND  C.CreateDtTm < (SELECT MAX(EndTime) FROM #Times)
    

    This performed instantly as opposed to several minutes for the original code (obviously your results may vary) .

    I assume if I changed my data type in my main table to be NOT NULL, it would work as well, but I was not able to test this at this time due to system constraints.

    0 讨论(0)
  • 2020-11-28 08:01

    When SQL starts to optimize the query plan for the query with the variable it will match the available index against the column. In this case there was an index so SQL figured it would just scan the index looking for the value. When SQL made the plan for the query with the column and a literal value it could look at the statistics and the value to decide if it should scan the index or if a seek would be correct.

    Using the optimize hint and a value tells SQL that “this is the value which will be used most of the time so optimize for this value” and a plan is stored as if this literal value was used. Using the optimize hint and the sub-hint of UNKNOWN tells SQL you do not know what the value will be, so SQL looks at the statistics for the column and decides what, seek or scan, will be best and makes the plan accordingly.

    0 讨论(0)
提交回复
热议问题