When executing the following script, I get the error:
Msg 207, Level 16, State 1, Line 15 Invalid column name ‘b’.
Anyone can explain it please? Thanks.
DROP TABLE ttt;
CREATE TABLE ttt(a nvarchar)
IF NOT EXISTS ( SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.ttt')
AND name = 'b' )
AND EXISTS ( SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.ttt')
AND name = 'a' )
BEGIN
ALTER TABLE [dbo].ttt ADD b NVARCHAR
UPDATE [dbo].ttt
SET b = a
ALTER TABLE [dbo].ttt DROP COLUMN a
END
It’s trying to compile all of these statements before it executes the 1st:
(In fact, it tries to compile the entire batch, not just these statements, but the point still stands – at the point it’s trying to compile the
UPDATE, the column does not exist)When it’s trying to compile the
UPDATEstatement, it consults the table metadata and correctly finds that the column doesn’t exist.Try
EXECing the update statement.And also, what Oded says about you probably wanting to specify a size for the column (otherwise, it defaults to the most pointless datatype ever – an
nvarchar(1))This script definitely runs without errors: