sql server - Optimize For in CTE or Subquery -
setup:
i'm experimenting optimize for
clause in sql server 2008 r2. i've put following @ end of query.
option (optimize (@usertype= 'm', @date unknown))
issue:
however, i'm getting below error.
the variable "@usertype" specified in optimize clause, not used in query.
this variable used in subquery within query, , used in location.
if try moving optimize for
subquery, stored proc not compile. likewise, cannot put subquery in cte , optimize within that; doesn't compile either.
incorrect syntax near keyword 'option'.
question:
is there way can use optimize for
clause within cte or subquery? i'd prefer use cte since cleaner , more legible.
the option
keyword must placed @ end of outer select query.
for example:
declare @var int = 1; cte ( select @var val ) select * cte option (optimize (@var = 2))