trigger creating table

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sentenza
    New Member
    • May 2010
    • 7

    trigger creating table

    I want to create a function that 'on update' and 'on insert' in table A column nome_tabella create another table named as the record just added in A:
    Code:
    CREATE FUNCTION trig_creazione_tabella() RETURNS trigger AS $$
    	BEGIN
    		IF (TG_OP = 'UPDATE') THEN
    	CREATE TABLE NEW.nome_tabella (id serial NOT NULL, sigla_comune character varying(4));
    		ELSIF (TG_OP = 'INSERT') THEN
    	CREATE TABLE NEW.nome_tabella (id serial NOT NULL, sigla_comune character varying(4));
    		END IF;
    	RETURN NEW;
    	END;
    $$ LANGUAGE plpgsql;
    on pgAdminIII i have an error on $1 (NEW.nome_tabel la) and i can't understand what's the problem, so I humbly ask help.

    Thanks to all
    Sentenza
    Last edited by rski; May 13 '10, 09:10 PM. Reason: Please use tags
  • rski
    Recognized Expert Contributor
    • Dec 2006
    • 700

    #2
    You should use dynamic SQL

    Code:
    CREATE FUNCTION trig_creazione_tabella() RETURNS trigger AS $$
    BEGIN
    IF (TG_OP = 'UPDATE') THEN
    EXECUTE 'CREATE TABLE '||NEW.nome_tabella||' (id serial NOT NULL, sigla_comune character varying(4))';
    ELSIF (TG_OP = 'INSERT') THEN
    EXECUTE 'CREATE TABLE '||NEW.nome_tabella||' (id serial NOT NULL, sigla_comune character varying(4))';
    END IF;
    RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;

    Comment

    • sentenza
      New Member
      • May 2010
      • 7

      #3
      perfect, now it works fine!

      thank you very much!!

      bye Sentenza

      Comment

      Working...