I am trying to get a psql function that would truncate a given table name if it exists. I've been trying multiple functions, but none of them worked so far. Here is the code :
CREATE OR REPLACE FUNCTION truncateIfExists(tableName TEXT) returns void as $$ BEGIN EXECUTE format( 'IF EXISTS ( SELECT * FROM information_schema.tables WHERE table_name =' || tableName || ' ) THEN TRUNCATE tableName; END IF; '); END; $$language plpgsql
Now, I am able to get it to work in a simple procedure with a harcoded name :
do $$ begin IF EXISTS (SELECT * FROM information_schema.tables WHERE table_name = genre_epf) THEN TRUNCATE genre_epf; END IF; end $$;
But I can't wrap my head on how to mix both queries. What am I doing wrong here ?