0
votes

When creating the following function in PostgreSQL, I get

ERROR: relation with OID 80424 does not exist CONTEXT: SQL function "test_update_icd_code" statement 7 SQL state: 42P01

So how do I create a table within a function?

(Note: the table will be deleted at the completion of the function.)

TIA

CREATE OR REPLACE FUNCTION test_update_icd_code()
    RETURNS void
AS $$   


-- Create a test table that references dx_log.
DROP TABLE IF EXISTS test;

CREATE TABLE test
(
    recid serial PRIMARY KEY,
    dx_log_recid integer NOT NULL,
    CONSTRAINT test_dx_log_fk FOREIGN KEY (dx_log_recid)
        REFERENCES dx_log (recid) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE RESTRICT
)
WITH (
    OIDS = FALSE
);

-----------

$$  LANGUAGE 'sql' VOLATILE;
1
I was able to create the function fine as-is (copy/paste). When I ran it, I got the "table does not exist" error. I changed nova.test to test and now it works OK. Have you tried removing the nova qualifier? - ravioli
@ravioli Yes...The code runs fine outside of the function. It's when it is run from within the function that the error occurs. How to fix it within the function? ('Nova' was only added after I received the error) - Alan Wayne
@ravioli Studied the provided reference. I am using language SQL; I do not get why I would need format; and the table I am creating is both created and destroyed within the same function??? - Alan Wayne
Please see my comments in the answer section. - ravioli

1 Answers

0
votes

Not sure why your function call isn't working. I took the code you have above, ran it through psql and it seems to work OK:

postgres=# DROP TABLE IF EXISTS test;
DROP TABLE
postgres=# DROP TABLE IF EXISTS dx_log;
DROP TABLE
postgres=# CREATE TABLE dx_log (recid INTEGER PRIMARY KEY) ;
CREATE TABLE
postgres=# CREATE OR REPLACE FUNCTION test_update_icd_code()
postgres-#     RETURNS void
postgres-# AS $$
postgres$#
postgres$# -- Create a test table that references dx_log.
postgres$# DROP TABLE IF EXISTS test;
postgres$#
postgres$# CREATE TABLE test
postgres$# (
postgres$#     recid serial PRIMARY KEY,
postgres$#     dx_log_recid integer NOT NULL
postgres$#  ,CONSTRAINT test_dx_log_fk FOREIGN KEY (dx_log_recid) REFERENCES dx_log (recid) MATCH SIMPLE ON UPDATE CASCADE ON DELETE RESTRICT
postgres$# )
postgres$# WITH (
postgres$#     OIDS = FALSE
postgres$# );
postgres$#
postgres$# -----------
postgres$#
postgres$# $$  LANGUAGE 'sql' VOLATILE;
CREATE FUNCTION
postgres=# SELECT test_update_icd_code();
NOTICE:  table "test" does not exist, skipping
 test_update_icd_code
----------------------

(1 row)


postgres=# SELECT * FROM test
postgres-# ;
 recid | dx_log_recid
-------+--------------
(0 rows)

How are you calling the function -- actual command, what client? Is the function erroring out before it even gets to the CREATE TABLE? What if you comment out the DROP TABLE and run the function -- what does it do?

I am testing from Postgres 10.0