I am little bit stucked with task IF EXIST.
I have several lines query with the COMMENTS ON TABLE function
COMMENT ON TABLE my_table1 IS 'Comment for table1';
COMMENT ON TABLE my_table2 IS 'Comment for table2';
COMMENT ON TABLE my_table3 IS 'Comment for table3';
COMMENT ON TABLE my_table3 IS 'Comment for table4';
I want to do, when I will execute this query, if one of the table doesn't exist query will pass that and continue.
I tried to do that task with IF EXIST action, but it doesn't works like UPDATE or other actions. Where am I wrong?
IF EXISTS (SELECT relname FROM pg_class where relname='my_table1')
then
COMMENT ON TABLE my_table1 IS 'Comment for table1';
IF EXISTS (SELECT relname FROM pg_class where relname='my_table2')
then
COMMENT ON TABLE my_table1 IS 'Comment for table2';
IF EXISTS (SELECT relname FROM pg_class where relname='my_table3')
then
COMMENT ON TABLE my_table1 IS 'Comment for table3';
IF EXISTS (SELECT relname FROM pg_class where relname='my_table4')
then
COMMENT ON TABLE my_table1 IS 'Comment for table4';
You could use:
DO
$do$
BEGIN
  IF EXISTS (SELECT relname FROM pg_class where relname='my_table1') THEN
    COMMENT ON TABLE my_table1 IS 'Comment for table1';
  END IF;
  IF EXISTS (SELECT relname FROM pg_class where relname='my_table2') THEN
    COMMENT ON TABLE my_table1 IS 'Comment for table2';
  END IF;
END
$do$
And check:
SELECT relname, obj_description(oid) 
FROM pg_class 
WHERE relname LIKE 'my_table%';
DBFiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With