SQL Server Query: Fast with Literal but Slow with Variable

前端 未结 8 1791
清歌不尽
清歌不尽 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 08:06

    In my case in DB table column type was defined as VarChar and in parameterized query parameter type was defined as NVarChar, this introduced CONVERT_IMPLICIT in the actual execution plan to match data type before comparing and that was culprit for sow performance, 2 sec vs 11 sec. Just correcting parameter type made parameterized query as fast as non parameterized version.

    Hope this may help someone with similar issue.

    0 讨论(0)
  • 2020-11-28 08:10
    DECLARE @id INT = 1
    
    SELECT * FROM View1 WHERE ID = @id
    

    Do this

    DECLARE @sql varchar(max)
    
    SET @sql = 'SELECT * FROM View1 WHERE ID =' + CAST(@id as varchar)
    
    EXEC (@sql)
    

    Solves your problem

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