Generally, parameterized identifiers are not allowed in SQL.
In a PL/pgSQL function this can be circumvented with a dynamic SQL string executed by EXECUTE
. Be wary of SQL injection. Column names have to be treated like user input.
DECLARE
_rec record;
_ct integer;
BEGIN
FOR _rec IN
SELECT ...
LOOP
EXECUTE format(
'SELECT count(*) FROM tblTraining
WHERE tbltraining.%I = 4', _rec.name); -- %I avoids SQL injection
INTO _ct;
IF _ct = 0 THEN ...
END LOOP;
format()
with %I
sanitizes strings to be valid identifiers. Prevents syntax errors and SQL injection. Be aware that unquoted identifiers are always cast do lower case in Postgres. If your true column names are lower-cased, you have to provide the lower-cased version here.
Never use CaMeL-case identifiers in Postgres to avoid all related problems to begin with.
Try a search for plgsql + dynamic-sql for many more examples: