2012-11-27 73 views
1

我想在plpgsql中創建一個Postgres存儲函數,該函數根據輸入參數創建具有指定列名稱的表。plpgsql存儲函數,用於創建具有參數列名稱的表

基本上是這樣的:

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

執行 '....' 使用(參數) – Shalin

+0

哪些數據假設函數返回? 「RETURNS bigint」 – Borys

回答

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; 

或者,如果你想使用 '使用' 條款:

[...] 
    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; 
[...] 
相關問題