I want to write execute block that I can use for multiple databases with similar structure, some don't have 1 or more tables. I use something like this
execute block as
begin
delete from table1;
delete from table2;
delete from table3;
delete from table4;
delete from table5;
end
and this works for base with all tables, but when table is missing the execute block stops. I want to use this execute block when there is missing table so I don't have to commit the missing one.
You can't do it like this. A table referenced in a
delete
PSQL statement must exist for theexecute block
to successfully compile before it can even run.Instead you will need to use statement blocks containing a
execute statement
to execute the statements dynamically and awhen any
exception handler to continue on any error.For example, something like:
You could also check for existence in the system tables before executing the delete dynamically. For example, something like:
The table names in the
IN
-clause must match the name as stored (for unquoted object names liketable1
that means uppercaseTABLE1
). Thereplace(tablename, '"', '""')
is just for completeness to escape possible double quotes in table names.