简体   繁体   English

postgres函数内部的准备好的语句

[英]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. 我可以在MySQL中执行以下操作,但想知道如何在PostgreSQL中进行等效操作。 I have to wrap the query in a string because the table name is variable (can't just run CREATE TABLE ). 我必须将查询包装在字符串中,因为表名是可变的(不能只运行CREATE TABLE )。 This is all in a MySQL stored procedure / Postgres function. 这全部在MySQL存储过程/ Postgres函数中。

    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? 有人可以告诉我如何在Postgres中执行此操作吗?

To run it once , just run the concatenated CREATE TABLE statement. 要运行一次 ,只需运行串联的CREATE TABLE语句。

To encapsulate the functionality for repeated use with variable table name, use a plpgsql function with EXECUTE : 要封装功能以与变量表名称重复使用,请使用带有EXECUTE的plpgsql函数:

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: 使用串行列在Postgres中实现AUTOINCREMENT

You might want to make the column PRIMARY KEY as well. 您可能还希望将列PRIMARY KEY为。
And varchar(255) rarely makes sense. 而且varchar(255)几乎没有道理。 I would just use text instead: 我只用text代替:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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