SQL Server Query: Fast with Literal but Slow with Variable

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

提交回复
热议问题