I want to execute a dynamic SQL statement, with its returned value being the conditional for an IF statement:
IF EXECUTE 'EXISTS (SELECT 1 FROM mytable)' THEN
This generates the error ERROR: type "execute" does not exist.
Is it possible to do this, or is it necessary to execute the SQL before the IF statement into a variable, and then check the variable as the conditional?
This construct is not possible:
IF EXECUTE 'EXISTS (SELECT 1 FROM mytable)' THEN ...You can simplify to:
But your example is probably simplified. For dynamic SQL executed with
EXECUTE, read the manual here. You can check the special variableFOUNDimmediately after executing any DML command to see whether any rows here affected:However:
Bold emphasis mine. For a plain
EXECUTEdo this instead:Or if opportune – in particular with only single-row results – use the
INTOclause withEXECUTEto get a result from the dynamic query directly. I quote the manual here: