Sunday, October 25, 2020

ORA-14551: cannot perform a DML operation inside a query

 Scenario:

SQL> DROP TABLE t PURGE;
Table T dropped.

SQL> CREATE TABLE t (
  2      c1 INT GENERATED AS IDENTITY
  3  );
Table T created.

SQL> INSERT INTO t VALUES ( DEFAULT );
1 row inserted.

SQL> INSERT INTO t VALUES ( DEFAULT );
1 row inserted.

SQL> COMMIT;
Commit complete.

SQL> SELECT * FROM t;
   C1
_____
    1
    2

SQL> CREATE OR REPLACE FUNCTION f RETURN INT AS
  2      retval INT;
  3  BEGIN
  4      INSERT INTO t VALUES ( DEFAULT ) RETURNING c1 INTO retval;
  5      RETURN retval;
  6  END f;
  7  /
Function F compiled

SQL> SELECT f FROM t;
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "DONGHUA.F", line 4

SQL> WITH x AS (
  2      SELECT /*+ materialize */ f FROM t
  3  )
  4  SELECT *
  5  FROM x;
   F
____
   4
   3

Testing script:

DROP TABLE t PURGE;

CREATE TABLE t (
    c1 INT GENERATED AS IDENTITY
);

INSERT INTO t VALUES ( DEFAULT );
INSERT INTO t VALUES ( DEFAULT );
COMMIT;

SELECT * FROM t;


CREATE OR REPLACE FUNCTION f RETURN INT AS
    retval INT;
BEGIN
    INSERT INTO t VALUES ( DEFAULT ) RETURNING c1 INTO retval;
    RETURN retval;
END f;
/

SELECT f FROM t;

WITH x AS (
    SELECT /*+ materialize */ f FROM t
)
SELECT *
FROM x;

No comments:

Post a Comment