T-Sql appears to be evaluating “If” statement even when the condition is not true

后端 未结 2 547
失恋的感觉
失恋的感觉 2020-12-20 17:19

I have a T-Sql script where part of this script checks to see if a certain column exists in the a table. If so, I want it to execute a routine... if not, I want it to bypas

相关标签:
2条回答
  • 2020-12-20 17:56

    Make your statement a string. And if column exists, execute it

    IF COL_LENGTH('Database_Name.dbo.Table_Name', 'Column_Name1') IS NOT NULL
    BEGIN
        DECLARE @sql VARCHAR(MAX)
        SET @sql = 'UPDATE Table_Name
                SET Column_Name2 = (SELECT Column_Name3 FROM Table_Name2
                    WHERE Column_Name4 = ''Some Value'')
                WHERE Column_Name5 IS NULL;
    
            UPDATE Table_Name
                SET Column_Name6 = Column_Name1
                WHERE Column_Name6 IS NULL;'
         EXEC(@sql)
    END
    
    0 讨论(0)
  • 2020-12-20 18:02

    SQL Server parses the statement and validates it, ignoring any if conditionals. This is why the following also fails:

    IF 1 = 1
    BEGIN
      CREATE TABLE #foo(id INT);
    END
    ELSE
    BEGIN
      CREATE TABLE #foo(id INT);
    END
    

    Whether you hit Execute or just Parse, this results in:

    Msg 2714, Level 16, State 1
    There is already an object named '#foo' in the database.

    SQL Server doesn't know or care which branch of a conditional will be entered; it validates all of the statements in a batch anyway. You can do things like (due to deferred name resolution):

    IF <something>
    BEGIN
      SELECT foo FROM dbo.Table_That_Does_Not_Exist;
    END
    

    But you can't do:

    IF <something>
    BEGIN
      SELECT column_that_does_not_exist FROM dbo.Table_That_Does;
    END
    

    The workaround, typically, is to use dynamic SQL:

    IF <something>
    BEGIN
      DECLARE @sql NVARCHAR(MAX);
      SET @sql = N'SELECT column_that_does_not_exist FROM dbo.Table_That_Does;';
      EXEC sp_executesql @sql;
    END
    
    0 讨论(0)
提交回复
热议问题