• No, it doesn't know the value, nor can it with the code you posted.

    The optimiser does not and can not execute queries (that's what the query execution engine does). So at the point of compile (and compilation for the batch takes place before any of the statements in the batch get executed), that variable has no value and it does not get a value until execution time (which is after all the queries have been compiled). The optimiser can't execute that SET command and see what the value is, because it does not execute any SQL.

    You can force a recompile (send the query back to the optimiser after part of the batch has been executed) with the recompile hint.

    DECLARE @fromdate_copy datetime

    SET @fromdate_copy = '20000101'

    SELECT * FROM Orders WHERE OrderDate > @fromdate_copy OPTION (RECOMPILE)

    That means that part way through execution, after the variable has a value, the query will be sent back to the optimiser to be recompiled, and since at that point the variable has a value, the optimiser can optimise based on that value.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass