【问题标题】:In an OUTPUT clause in an INSTEAD OF INSERT trigger, is it possible to reference both INSERTED tables?在 INSTEAD OF INSERT 触发器的 OUTPUT 子句中,是否可以引用两个 INSERTED 表?
【发布时间】:2010-10-21 19:32:14
【问题描述】:

SQL Server 2005+

我有一个带有INSTEAD OF INSERT 触发器的视图。在触发器的主体内,我想使用带有 OUTPUT 子句的语句,它引用了两个 INSERTED 表:

  • INSTEAD OF INSERT 触发器的外部 INSERTED
  • OUTPUT 子句的内部 INSERTED

MSDNsays this:

如果在触发器的主体内使用包含 OUTPUT 子句的语句,则必须使用表别名来引用触发器的插入和删除表,以避免与与 OUTPUT 关联的 INSERTED 和 DELETED 表重复列引用。

但别名似乎不起作用:

CREATE TRIGGER v_insert ON v
INSTEAD OF INSERT
AS BEGIN
  INSERT INTO t (a, b, c)
  OUTPUT inserted.a, inserted.b, outer_inserted.d INTO t_prime (a, b, d)
  SELECT a, b, c
  FROM inserted as outer_inserted
END

它产生错误“无法绑定多部分标识符“outer_inserted.d”。这是否意味着我尝试做的事情是不可能的?

【问题讨论】:

    标签: sql-server triggers


    【解决方案1】:

    我读它是因为在您访问触发器 INSERTED 的 FROM 中需要 INSERTED 别名。

    OUTPUT 子句中的 INSERTED 只能引用插入到 t 中的数据。

    所以你的 OUTPUT 子句中不能有 outer_inserted.d

    你也不能这样,我是这么看的

    INSERT INTO t (a, b, c)
      OUTPUT inserted.a, inserted.b INTO t_prime (a, b)
      SELECT a, b, c
      FROM inserted --no alias = **FAIL**
    

    【讨论】:

    • 是的,重要的一点似乎是只有 DELETE、UPDATE 和 MERGE 语句可以在 OUTPUT 子句中引用除 INSERTED 之外的表。在 INSERT 语句中,它只能引用 INSERTED。
    【解决方案2】:

    这有点旧,但是您缺少 SELECT from outer_inserted 表中的 d 列,因此您无法在 OUTPUT 中引用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多