当我将它放入 SQL Server 2008 R2 Management Studio 时,它以某种方式起作用:
if 1 = 1
begin
create table foo (
p int
);
alter table foo
add v int;
insert into foo values (1, 2)
select v from foo;
end
GO
这表示列名 v 无效:
create table foo (
p int
);
go;
if 1 = 1
begin
/* create table foo (
p int
);*/
alter table foo
add v int;
insert into foo values (1, 2)
select v from foo;
end
GO
这很好用:
create table foo (
p int
);
go
if 1 = 1
begin
/* create table foo (
p int
);*/
alter table foo
add v int;
insert into foo values (1, 2)
-- select v from foo;
end
GO
这是另一个例子,它也能正常工作:
create table foo (
p int
);
go
if 1 = 1
begin
alter table foo
add v int not null;
alter table foo
add constraint PK_foo primary key(v);
end
GO
文档里说的很清楚: http://technet.microsoft.com/en-us/library/ms175502(v=sql.105).aspx
A table cannot be changed and then the new columns referenced in the same batch.
看来,如果表是在批处理中创建的,那很好,或者如果您在批处理中为添加的列创建约束,那也很好。但是,如果您为该列发出 DML 查询(选择),则会出现错误。
为什么会这样?
最佳答案
就我而言(SQL Server 2008 R2 Dev)示例 #1、#3 和 #4 有效。
从 Martin Smith 的评论(延迟编译)开始,我创建了一个显示 the cause 的 SQL Trace。 (参见表 7:为 SP:Recompile 事件报告的重新编译原因)对于 [re]compilation(s)
在所有情况下(#1、#3、#4),由于延迟编译(“由于 DNR(延迟名称解析)而重新编译。在编译时未找到对象,将检查延迟到运行时。”),此批处理有效。 ).
示例 #3 的输出(带有 COMMIT:“我打印错误的第三个案例,有一个提交而不是 go”):
示例 #4 的输出:
关于sql-server - 我对 SQL Server 批处理很困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20773533/