Stored Procedure vs Function in PostgreSQL for DML Statements

postgresqlpostgresql-9.3stored-procedures

I'm using postgresql 9.3. If I want to add the following steps and call these steps as a routine, would it be better to use a function or stored procedure?

My basic steps are:

RENAME TABLE FOOBAR_1234.table1_org TO FOOBAR_1234.table1_old;
DELETE FOOBAR_1234.table1_old WHERE 1=1;
RENAME TABLE FOOBAR_1234.table1 TO FOOBAR_1234.table1_org;

What I also need is the flexibility to parameterize the ID as in 1234 with any ID, example 5678.

If you have an example, that would be helpful too.

Best Answer

There is no such thing as a stored procedure in PostgreSQL. All PostgreSQL has are SQL-callable functions defined in a number of languages - LANGUAGE sql, LANGUAGE plpgsql, LANGUAGE plperl, etc.

Additionally, there's no RENAME TABLE command. You want ALTER TABLE ... RENAME TO ....

This particular example must be written in PL/PgSQL using EXECUTE because it relies on dynamic SQL. See the numerous existing examples on Stack Overflow of using PL/pgSQL EXECUTE. Something like a PL/PgSQL function with:

EXECUTE format('ALTER TABLE %I.%I RENAME TO %I.%I;',
    'FOOBAR_'||_schema_id, 'table1_org',
    'FOOBAR_'||_schema_id, 'table1_old');

Edit: OK, more complete example:

CREATE OR REPLACE FUNCTION myfunc(_schema_id integer)
RETURNS void LANGUAGE plpgsql AS $$
BEGIN
    EXECUTE format('ALTER TABLE %I.%I RENAME TO %I.%I;',
        'FOOBAR_'||_schema_id, 'table1_org',
        'FOOBAR_'||_schema_id, 'table1_old');

    -- Now TRUNCATE the table and do your second `RENAME`
    -- in subsequent EXECUTE statements.
END;
$$;