合并中的Oracle 11g错误使用insert语句中的新记录上的链接

时间:2015-11-20 16:32:53

标签: oracle oracle11g sql-merge

我有两张桌子:

initWithCGImage

和内容:

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

它有效。

为什么新记录上的链接在update语句中有效,但在insert语句中不起作用?

1 个答案:

答案 0 :(得分:1)

试试这个......注意MERGE的变化......

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

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>

或者验证/测试INSERT部分:

  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>