Search code examples
sql-server-2008compiler-errorsssmsevaluationindexed-view

Does SQL Server Management Studio (or SQL Server) evaluate *all* expressions?


Here's my configuration:

  • I have a re-runnable batch script that I use to update my database.
  • Inside of that batch script, I have code that says the following:
    • If Table 'A' doesn't exist, then create Table 'A' and insert rows into it.
  • Later on in that batch script, I create an schemabound indexed view on that table.
  • Sometimes, when I re-run the script, that is after the table has been created, SQL Server Management Studio evaluates the "insert rows" code, which is protected by the 'If this table doesn't exist' code, and yields the following error:

    Msg 1934, Level 16, State 1, Line 15 INSERT failed because the following SET options have incorrect settings: 'CONCAT_NULL_YIELDS_NULL, ANSI_WARNINGS, ANSI_PADDING, ARITHABORT'. Verify that SET options are correct for use with indexed views and/or indexes on computed columns and/or filtered indexes and/or query notifications and/or XML data type methods and/or spatial index operations.

  • Please note: If someone were to try this INSERT statement in a vacuum, I would fully expect SSMS to generate this error.
    • But not when it's protected by a conditional block.

My Question:

Does the SSMS compiler evaluate all expressions, regardless of whether they will actually be executed?


Solution

  • Yes, it evaluates all of them,take a look at this

    declare @i int
    select @i =1
    
    if @i = 1
    begin
        declare @i2 int
        set @i2 = 5
    end
    else 
    begin
        declare @i2 int
        set @i2 = 5
    end
    

    Msg 134, Level 15, State 1, Line 12 The variable name '@i2' has already been declared. Variable names must be unique within a query batch or stored procedure.

    Another example with temp tables is here: What is deferred name resolution and why do you need to care?

    your only way out would be to wrap it inside dynamic SQL