1

我想在 plpgsql 中创建一个 Postgres 存储函数,该函数创建一个具有根据输入参数而变化的指定列名的表。

基本上是这样的:

CREATE OR REPLACE FUNCTION document_insert_new_document(_name text, _table_name text)
  RETURNS bigint AS
$BODY$
declare
  _documentid bigint;
  _user_history_table_name text;
  _history_table_name_column text;

begin
    _documentid = 0;
    _user_history_table_name = 'merge_user_history_' || _table_name;
    _history_table_name_column = _table_name || '_id';
    CREATE TABLE _user_history_table_name
    (
      user_history_id bigint NOT NULL,
      _history_table_name_column bigint NOT NULL,
      ...
    )



end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

这可能吗?如果是这样,怎么办?

4

1 回答 1

1
CREATE OR REPLACE FUNCTION document_insert_new_document(_name text, _table_name text)
  RETURNS void AS
$BODY$
declare
  _documentid bigint;
  _user_history_table_name text;
  _history_table_name_column text;
  query_create text;

begin
    _documentid = 0;
    _user_history_table_name = 'merge_user_history_' || _table_name;
    _history_table_name_column = _table_name || '_id';
    query_create := 'CREATE TABLE ' || _user_history_table_name ||
                    ' (user_history_id bigint NOT NULL,' ||
                    _history_table_name_column ||
                    ' bigint NOT NULL,
                     ... ) 
                    WITH (
                    OIDS=FALSE
                    )';
    EXECUTE query_create;

end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

或者,如果你想使用 'USING' 子句:

[...]
    query_create := 'CREATE TABLE ($1) (
                     user_history_id bigint NOT NULL,
                     ($2) bigint NOT NULL,
                     ... ) 
                     WITH (
                     OIDS=FALSE
                     )';
    EXECUTE query_create USING _user_history_table_name, _history_table_name_column;
[...]
于 2012-12-03T10:18:03.940 回答