sql-server - 我对 SQL Server 批处理很困惑

标签 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

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”): enter image description here

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

关于sql-server - 我对 SQL Server 批处理很困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20773533/

相关文章:

sql - 按日期字段的月份排序记录

sql-server - ARITHABORT OFF 对性能产生不利影响

mysql - 如何在 SQL where 子句中使用 if 条件应用用户过滤器?

sql - 为什么插入单行比一次插入 x 行快 x 倍

sql-server - SQL 服务器 2008 R2 : Update with condition

node.js - 如何使用存储过程是sequelize orm

c# - 我需要将 2 列的数据合并到另一列。然后将该添加列的所有行合并到另一个表中的一个单元格中

sql-server-2005 - 为什么我的 CASTS 在 SSIS 中似乎被忽略了?

sql-server - "DROP USER"最多需要 30 秒

SQL Server合并复制权限问题