tags:

views:

39

answers:

2

Below is an excerpt of a SQL Query that I am using to update a table to the correct datatypes if needed.

If NOT Exists(Select * From Information_Schema.Columns 
    Where Table_Name = N'RXINFO'
    And Table_Schema = N'scriptassist' 
    And Column_Name = N'LastChanged'    
    And DATA_Type = N'TIMESTAMP' 
    AND IsNull(CHARACTER_MAXIMUM_LENGTH, 0) = 0)
     BEGIN
      Print 'LastChanged Field  needed type updating'
      Alter Table [scriptassist].[RXINFO] Alter Column LastChanged TIMESTAMP
     END

Currently the problem is as follows:

If I run the statement With the Alter Table present SQL Server throws this error at me.

Msg 4927, Level 16, State 1, Line 12 Cannot alter column 'LastChanged' to be data type timestamp.

The problem isn't that it can't change the Datatype the problem is that it is attempting to execute that code block regardless of the evaluation of the Condition. It should evaluate to False in this case.

If I take it out, nothing happens, the print statement doesn't even fire.

The only thing that I can think of thus far is that somehow MS SQL is evaluation the SQL beforehand and determining if all the code paths can execute, and since they can't it throws the error. However this doesn't make that much sense.

+3  A: 

SQL Server parses your SQL before it executes it. The error is raised during parsing.

To delay parsing until the line is actually run, use exec:

exec ('Alter Table [scriptassist].[RXINFO] Alter Column LastChanged TIMESTAMP')
Andomar
@Andomar perfect thank you.
msarchet
I just tested this and you'll still get the same error. See [my answer](http://stackoverflow.com/questions/4017731/alter-table-executing-regardless-of-condition-evaluational-results/4017902#4017902) instead.
Joe Stefanelli
@Joe Stefanelli makes a good point. The Exec() solution prevents the ALTER COLUMN code from being evaluated when it's not supposed to run. BOL says the ALTER column "type_name cannot be timestamp" -- http://msdn.microsoft.com/en-us/library/ms190273.aspx
KenJ
+2  A: 

I believe you're getting this error because SQL cannot perform a conversion from the previous datatype of your TimeStamp column to an actual TimeStamp datatype. You'll need to drop and then add the column instead.

If NOT Exists(Select * From Information_Schema.Columns 
    Where Table_Name = N'RXINFO'
    And Table_Schema = N'scriptassist' 
    And Column_Name = N'LastChanged'    
    And DATA_Type = N'TIMESTAMP' 
    AND IsNull(CHARACTER_MAXIMUM_LENGTH, 0) = 0)
     BEGIN
      Print 'LastChanged Field  needed type updating'
      Alter Table [scriptassist].[RXINFO] Drop Column LastChanged
      Alter Table [scriptassist].[RXINFO] Add LastChanged TimeStamp
     END
Joe Stefanelli
+1 My answer guards against non-existing columns, but that makes no sense on re-reading the question.
Andomar