我对SQL Server批处理非常困惑

时间:2013-12-25 13:58:49

标签: sql-server sql-server-2008-r2

当我将它放入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

  

无法更改表,然后在中引用新列   同一批。

似乎如果在批处理中创建了表格,或者如果您正在为批处理中添加的列创建约束,那也没关系。但是,如果您要为该列发出DML查询(选择),则会收到错误。

为什么它会像这样?

1 个答案:

答案 0 :(得分:4)

就我而言(SQL Server 2008 R2 Dev),示例#1,#3和#4有效。

从Martin Smith的评论(延迟编译)开始,我创建了一个SQL Trace,它显示了the cause(参见表7:针对SP重新编译事件报告的重新编译原因)[re]编译

在所有情况下(#1,#3,#4),此批次的工作原因是延迟编译(“由于DNR(延迟名称解析)而重新编译。在编译时未找到对象,延迟检查到运行时间。” )。

例如#3的输出(使用COMMIT:“我错误打印了第3个案例,有一个提交而不是去”): enter image description here

例如#4的输出: enter image description here

相关问题