1

In the trigger body, how can I get a value of NEW by the field name?

This is what I want to do:

some_key = "some_column";

value := NEW[some_key];
1
  • This is not possible. May be you could explain the problem you're trying to solve, instead of your impossible solution to that problem. Commented Nov 16, 2019 at 14:12

1 Answer 1

1

You have to use dynamic SQL like this:

EXECUTE format('SELECT $1.%I', some_key) INTO value USING NEW;
2
  • Your solution is correct, thank you very much. I managed to solve the problem. See part of the code. code FOR ri IN SELECT ordinal_position, column_name, data_type FROM information_schema.columns WHERE table_schema = quote_ident(TG_TABLE_SCHEMA) AND table_name = quote_ident(TG_TABLE_NAME) AND column_name = quote_ident(nmpk) ORDER BY ordinal_position LOOP EXECUTE 'SELECT ($1).' || ri.column_name || '::text' INTO t USING NEW; idValue := t; END LOOP; Commented Nov 19, 2019 at 10:22
  • 1
    If the answer is correct, you might accept it. Concatenating column names with || is a bad idea because of the risk of SQL injection. Use the format function like I did in my answer. Commented Nov 19, 2019 at 10:30

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.