我想在plpgsql中创建一个Postgres Stored函数,它创建一个具有指定列名的表,这些列根据输入参数而变化。
基本上是这样的:
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;
这可能吗?如果是这样,怎么样?
答案 0 :(得分: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;
[...]