在插入语句中的新记录上使用 link 进行合并时出现 Oracle 11g 错误

Oracle 11g error in merge using link on new record in insert statement

我有两个表:

CREATE TABLE
    test
    (
        id INTEGER,
        str VARCHAR2(10)
    );
CREATE TABLE
    test2
    (
        id INTEGER,
        tmp VARCHAR2(10)
    );

和内容:

INSERT INTO test2   (id,    tmp)    VALUES (    10,'tmp10');
INSERT INTO test2   (id,    tmp)    VALUES (    20,'tmp20');

当我运行下一个脚本时:

MERGE INTO  test mt
USING   (
        SELECT
            1  AS id,
            10 AS id2
        FROM
            dual) nr
ON  (   mt.id=nr.id)
WHEN MATCHED THEN
   UPDATE SET str=(SELECT   id  FROM test2  WHERE       id=nr.id2)
WHEN NOT MATCHED    THEN 
   INSERT   (id,str)    VALUES (    nr.id,(SELECT   tmp FROM    test2   WHERE   id=nr.id2) );

我看到错误:

[Error Code: 904, SQL State: 42000]  ORA-00904: "NR"."ID2": invalid identifier

但是当我运行:

MERGE INTO  test mt
USING   (
        SELECT
            1  AS id,
            10 AS id2
        FROM
            dual) nr
ON  (   mt.id=nr.id)
WHEN MATCHED THEN
   UPDATE SET str=(SELECT   id  FROM test2  WHERE       id=nr.id2)
WHEN NOT MATCHED    THEN 
   INSERT   (id,str)    VALUES (    nr.id,(SELECT   tmp FROM    test2   WHERE   id=10) );

有效。

为什么 link on new record 在 update 语句中有效,但在 insert 语句中无效?

试试这个...注意对 MERGE 的更改...

1) 在 USING 子句中,确保你有一个 FULL 查询,returns 你想要的结果..

2) 您的 INSERT 将直接从那里引用该值..而不是从 INSERT 子语句中的子查询..

  SQL> select * from test;

  no rows selected

  SQL> select * from test2;

          ID TMP
  ---------- ----------
          10 tmp10
          20 tmp20

  SQL> SELECT id, tmp
    2  FROM test2
    3   WHERE id IN ( 1, 10 )
    4  /

          ID TMP
  ---------- ----------
          10 tmp10

  SQL> MERGE INTO test mt
    2     USING (
    3        SELECT id, tmp
    4          FROM test2
    5         WHERE id IN ( 1, 10 )
    6         )  nr
    7     ON ( mt.id = nr.id )
    8     WHEN MATCHED THEN
    9        UPDATE set str = nr.tmp
   10     WHEN NOT MATCHED THEN
   11        INSERT ( id, str ) VALUES ( nr.id, nr.tmp )
   12  /

  1 row merged.

  SQL> commit;

  Commit complete.

  SQL> select * from test;

          ID STR
  ---------- ----------
          10 tmp10

  SQL>

或验证/测试插入部分:

  SQL> MERGE INTO test mt
    2     USING (
    3        SELECT id, tmp
    4          FROM test2
    5         WHERE id IN ( 1, 10, 20 )
    6         )  nr
    7     ON ( mt.id = nr.id )
    8     WHEN MATCHED THEN
    9        UPDATE set str = nr.tmp
   10     WHEN NOT MATCHED THEN
   11        INSERT ( id, str ) VALUES ( nr.id, nr.tmp )
   12  /

  2 rows merged.

  SQL> select * from test;

          ID STR
  ---------- ----------
          10 tmp10
          20 tmp20

  SQL>