问题:新建一个测试表xx
select 1 as code into xx select * from xx
给这个表添加一个列val, val列不允许为空,将表中已有的数据val值更新为1
alter table xx add val int null; update xx set val = 1 where 1=1; alter table xx alter column val int not null;
执行以上脚本会有以下错误:
Msg 207, Level 16, State 1, Line 2
Invalid column name 'val'.
解决办法:添加GO,说明连接
alter table xx add val int null; GO update xx set val = 1 where 1=1; alter table xx alter column val int not null;
More generally the problem is a parse/compile issue. SQL Server tries to compile all statements in the batch before executing any of the statements.