I have this SQL change script that runs as part of my nant orchestrated DB creation or update:
SET XACT_ABORT ON
BEGIN TRANSACTION
PRINT 'Change MyColumn column to MyNewColumn column in MyTable table'
IF EXISTS (SELECT *
FROM sys.columns
WHERE Name = 'MyColumn' AND Object_id = OBJECT_ID('[dbo].[MyTable]'))
BEGIN
PRINT '-> Exists, change it'
/* NOTE THE NEXT LINE */
SET @Value = (SELECT MyColumn FROM [dbo].[MyTable])
ALTER TABLE [dbo].[MyTable]
DROP CONSTRAINT DF_MyTable_MyColumn
ALTER TABLE [dbo].[MyTable]
DROP COLUMN MyColumn
ALTER TABLE [dbo].[MyTable]
ADD MyNewColumn nvarchar(20) NULL
ALTER TABLE [dbo].[MyTable]
ADD CONSTRAINT DF_MyTable_MyNewColumn DEFAULT ('') FOR MyNewColumn
PRINT '-> Add values back into table'
SET @Dynamic_Sql = 'UPDATE [dbo].[MyTable] SET MyNewColumn = ''' + @Value + ''''
EXEC(@Dynamic_Sql)
PRINT '-> Alter to NOT NULL'
ALTER TABLE [dbo].[MyTable]
ALTER COLUMN MyNewColumn nvarchar(20) NOT NULL
END
ELSE
BEGIN
PRINT '-> Does not exist, skip it'
END
I have already ran this update script before and made the changes to the DB (so MyColumn no longer exists). But now I have a new script that comes after this one, but my "build" fails on this line of this script with:
Msg 207, Level 16, State 1, Line 15 Invalid column name 'MyColumn'
where Line 15 is the FROM sys.columns line. But this is actually complaining about the line I have within the IF statement, where I have put in the NOTE comment. Why would this be the behaviour? Of course the column name will be invalid if it no longer exists.