I was writing a (seemingly) straight-forward SQL snippet that drops a column after it makes sure the column exists.
The problem: if the column does NOT exist, the code inside the IF clause complains that it can’t find the column! Well, doh, that’s why it’s inside the IF clause!
So my question is, why does a piece of code that shouldn’t be executed give errors?
Here’s the snippet:
IF exists (select * from syscolumns WHERE id=object_id('Table_MD') and name='timeout') BEGIN ALTER TABLE [dbo].[Table_MD] DROP COLUMN timeout END GO
…and here’s the error:
Error executing SQL script [...]. Invalid column name 'timeout'
I’m using Microsoft SQL Server 2005 Express Edition.
Reason: When Sql server compiles the code, they check it for used objects ( if they exists ). This check procedure ignores any ‘IF’, ‘WHILE’, etc… constructs and simply check all used objects in code.