1

I am trying to drop table if exists else proceed for next step in function using PostgreSQL 9.3 version.

Example:

  Create or replace function test(tablename varchar)
  returns setof record as
  $$
  Declare
        var1 varchar :='table_';
  Begin
        var1 :=var1 ||tablename;
        /* Here need to drop table if exists */
       drop table if exist var1;

       /* else proceed for next step */
       ....
       ....
   end;
   $$
   language plpgsql;
1
  • does drop table works in your Function ? Commented Jun 14, 2014 at 9:07

2 Answers 2

2

Try using EXECUTE

EXECUTE 'DROP TABLE IF EXISTS ' || var1;
Sign up to request clarification or add additional context in comments.

3 Comments

Made same change. But getting only notification that table does not exists not proceeding for next procedure.
@Meem the issue is likely in your next procedure then because IF EXISTS is supposed to show a notification if a table does not exist, so there is nothing wrong with seeing a notification
Yes! I got it. Thank you so much.
1

You need to run the DROP TABLE command as below using execute (As @FuzzyTree already pointed much before me)

execute 'drop table ' || var1;

(OR)

execute 'DROP VIEW ' || var1;

Also another pointer, DROP TABLE is not allowed in a non-volatile function. So you may have to change the last line of your function to be

LANGUAGE 'plpgsql' VOLATILE;

Check this post, Will get you better idea How to delete table *or* view from PostgreSQL database?

3 Comments

I did. But not proceeding for next step only giving notifying that table does not exists.
No! I have used it like "drop table if exists".
@Meem, You will have to use IF .. ELSE construct to conditionally do the dropping. check the link I have mentioned in answer. that will get you what you are trying to do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.