简体   繁体   中英

prepared statement inside function in postgres

I can do the following in MySQL, but would like to know how to do the equivalent in PostgreSQL. I have to wrap the query in a string because the table name is variable (can't just run CREATE TABLE ). This is all in a MySQL stored procedure / Postgres function.

    SET @createTable = CONCAT("CREATE TABLE ", table_name, "(
              id int(11) NOT NULL AUTO_INCREMENT,
              something varchar(255) NOT NULL");
    PREPARE createTableStmt FROM @createTable;
    EXECUTE createTableStmt;
    DEALLOCATE PREPARE createTableStmt;

Can someone please tell me how to do this in Postgres?

To run it once , just run the concatenated CREATE TABLE statement.

To encapsulate the functionality for repeated use with variable table name, use a plpgsql function with EXECUTE :

CREATE OR REPLACE FUNCTION create_my_table(_tbl text)
  RETURNS void AS
$func$
BEGIN
   EXECUTE format('CREATE TABLE %I (id serial, something varchar(255) NOT NULL)', _tbl);
END
$func$ LANGUAGE plpgsql;

Call:

SELECT create_my_table('foo_table');

To drop:

DROP create_my_table(text);

There are many related answers here. Try a search.

Or if you only need it for the current session you can make it a temporary function that is dropped at the end of the session automatically:

CREATE OR REPLACE FUNCTION pg_temp.create_my_table(_tbl text) ...

Use a serial column to implement AUTOINCREMENT in Postgres:

You might want to make the column PRIMARY KEY as well.
And varchar(255) rarely makes sense. I would just use text instead:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM