Is there a way to make a TSQL variable constant?

前端 未结 12 1049
别那么骄傲
别那么骄傲 2021-02-01 11:31

Is there a way to make a TSQL variable constant?

12条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 12:08

    My workaround to missing constans is to give hints about the value to the optimizer.

    DECLARE @Constant INT = 123;
    
    SELECT * 
    FROM [some_relation] 
    WHERE [some_attribute] = @Constant
    OPTION( OPTIMIZE FOR (@Constant = 123))
    

    This tells the query compiler to treat the variable as if it was a constant when creating the execution plan. The down side is that you have to define the value twice.

提交回复
热议问题