开发者

How to use a trigger in PostgreSQL to create a new schema when a new row is inserted in a table?

I have a table that holds clients, I have just one client per country, and for each row in this table I must create a new schema and replicate some tables. Like this:

Clients table's columns: 

client      country
----------  -----------
john doe    US
jane doe    UK

Schemas:

clients_US
clients_UK

I need to create a trigger to create those schemas automatically everytime a new client is added to the clients table, using the country column data as part of the schema's name.

In a perfect world this would work, but it clearly doesn't:

CREATE OR REPLACE FUNCTION gcpmanager.create_sle_schema() 
RETURNS trigger LANGUAGE plpgsql
AS
    'begin 
    CREATE SCHEMA "clients_" + new.country
    开发者_如何学CAUTHORIZATION postgres;
        return new;
    end;';


You will need to use dynamic SQL

CREATE OR REPLACE FUNCTION gcpmanager.create_sle_schema() 
RETURNS trigger LANGUAGE plpgsql
AS
$$
begin 
  execute 'CREATE SCHEMA clients_'||new.country||' AUTHORIZATION postgres';
  return new;
end;
$$

Btw: the string concatenation operator in PostgreSQL is || not + (that is for numbers)


Use dynamic SQL for this:

http://www.postgresql.org/docs/9.0/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜