This question is about Postgresql 8.3.
I've got a table with a field containing conditions like 'lastcontact is null'. In code, I want to loop through this table and for each record, I want to check 'if condition then', like in this example:
FOR myrec IN
SELECT * FROM tabel ORDER BY colorlevel, volgnummer
LOOP
if (myrec.conditie) then
raise notice 'Condition % is true', myrec.conditie;
else
raise notice 'Condition % is false', myrec.conditie;
end if;
END LOOP;
The table which I have called 'tabel' in this example:
ID | Conditie | Colorlevel | Volgnummer | Code | Description
1 | lastcontact is null | 1 | 1 | ... | ...
2 | lastchanged is null | 1 | 2 | ... | ...
3 | lastmodified is null | 1 | 3 | ... | ...
Is it possible to do the check I desire? The code above results in the following error:
ERROR: invalid input syntax for type boolean: "lastcontact is null"
New section containing the result of Erwin's function
I have used this function:
CREATE OR REPLACE FUNCTION foo(lastcontact timestamptz)
RETURNS void AS
$BODY$
DECLARE
myrec record;
mycond boolean;
BEGIN
FOR myrec IN
SELECT * FROM tabel ORDER BY colorlevel, volgnummer
LOOP
EXECUTE 'SELECT ' || myrec.conditie || ' FROM tabel' INTO mycond;
IF mycond then
RAISE NOTICE 'Condition % is true', myrec.conditie;
ELSE
RAISE NOTICE 'Condition % is false', COALESCE(myrec.conditie, 'NULL');
END IF;
END LOOP;
END;
$BODY$
language 'plpgsql' volatile
cost 100;
I get this error:
ERROR: column "lastcontact" does not exist
LINE 1: SELECT lastcontact is null FROM tabel
^
QUERY: SELECT lastcontact is null FROM tabel
CONTEXT: PL/pgSQL function "foo" line 9 at EXECUTE statement1
I tried to find an explanation myself, but to no avail. It obviously is trying to run the statement against the database, but it should understand that 'lastcontact' is the variable that's been given as a function parameter.
From the comments I finally think I understand. You need dynamic SQL:
Be aware, however, that this setup is wide open for SQL injection. Only use verified input. A function works in PostgreSQL 8.3 as well (no
DO
statements, yet).You cannot refer to parameters inside dynamic SQL (
EXECUTE
statement). You have to put the value into the query string.In PostgreSQL 8.4 or later you have the superior commodity of the
USING
clause. Alas, not in version 8.3. You should consider upgrading if you can.I put in a workaround for your old version. You have to take special care of the
NULL
value.