0

I'd pass as variable the schema name in a function with trigger

Function and trigger are so defined:

CREATE OR REPLACE FUNCTION test()  RETURNS TRIGGER AS $shp_create$

  BEGIN
    RAISE NOTICE 'NEW: %', NEW;
    IF NEW.log_type = false THEN

        INSERT INTO target_table
        SELECT * FROM $%%NEW.schema_or%%%.start_table 
    
        NEW.log_type := true;

      RETURN NEW;
    END IF;
    RETURN NEW;
  END;

 $test$ LANGUAGE plpgsql;


DROP TRIGGER IF EXISTS test_trigger ON table_log;
CREATE TRIGGER test_trigger BEFORE INSERT ON table_log
  FOR EACH ROW EXECUTE PROCEDURE test();

table_log is so defined:

log_type|schema_or
--------|---------
 false    test

So the Insert statment in the function become:

INSERT INTO target_table
SELECT * FROM test.start_table 

1 Answer 1

2

Per Dynamic query:

EXECUTE format('INSERT INTO target_table
        SELECT * FROM %I.start_table', NEW.schema_or )

This use the string function format to create a query string that can then be executed. Look at the format link for a full explanation of what is possible. In this case %I refers to an identifier, the schema name.

Sign up to request clarification or add additional context in comments.

1 Comment

Not sure why: format('INSERT INTO target_table SELECT string_agg(field::varchar,''-'') FROM %I.start_table', 'test' ); yielding: INSERT INTO target_table SELECT string_agg(field::varchar,'-') FROM test.start_table would not work? What is the error you get?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.