为什么引用不属于正在查询的 table 的列(作为左侧操作数)不是 EXISTS 运算符中的错误?

Why is referencing a column (as a left-hand operand) that is not part of the table being queried not an error in the EXISTS operator?

给定这个 SQL 批次:

CREATE TABLE #source
(
  ID int,
  SourceDescr varchar(255)
)
INSERT INTO #source
VALUES
(1, 'first'),
(2, 'second')


CREATE TABLE #target
(
  ID int,
  TargetDescr varchar(255)
)
INSERT INTO #target
SELECT * FROM #source

INSERT INTO #target
SELECT * FROM #source S
WHERE NOT EXISTS
(
  SELECT 1
  FROM #target
  WHERE SourceDescr = S.SourceDescr
  --       /\ How is this not an error?
)

为什么 EXISTS 运算符中的 WHERE 子句有效? #target table.

中肯定没有 SourceDescr

我什至试过了,它也有效:

INSERT INTO #target
SELECT * FROM #source S
WHERE NOT EXISTS
(
  SELECT SourceDescr -- ??
  FROM #target
  WHERE SourceDescr = S.SourceDescr
)

阅读官方documentation for EXISTS并没有为我澄清这一点。

谢谢。

这解释为:

INSERT INTO #target
    SELECT S.*
    FROM #source S
    WHERE NOT EXISTS
    (
      SELECT 1
      FROM #target
      WHERE S.SourceDescr = S.SourceDescr
    );

它运行了,但它没有按照您的预期运行。

这就是我建议在 all 查询中对 all 列引用使用限定列名称的原因之一。您的预期逻辑:

INSERT INTO #target
    SELECT S.*
    FROM #source S
    WHERE NOT EXISTS
    (
      SELECT 1
      FROM #target t
      WHERE t.SourceDescr = S.SourceDescr
    );

会产生编译时错误并且永远不会执行。

因为文档中有说明:Subqueries (SQL Server):

column names in a statement are implicitly qualified by the table referenced in the FROM clause at the same level. If a column does not exist in the table referenced in the FROM clause of a subquery, it is implicitly qualified by the table referenced in the FROM clause of the outer query.