From: | Joe Conway <mail(at)joeconway(dot)com> |
---|---|
To: | Kevin Coyner <kevin(at)rustybear(dot)com> |
Cc: | pgsql-novice(at)postgresql(dot)org |
Subject: | Re: drop table if exists |
Date: | 2003-03-14 17:46:26 |
Message-ID: | 3E721572.2050706@joeconway.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-novice |
Kevin Coyner wrote:
>>Is there an equivalent to "IF EXISTS" in Postgres?
>
No, there is no direct equivalent (and I have often wished there was --
but not enough to try to implement it, at least not yet).
You can fake it with a plpgsql function (very lightly tested):
CREATE OR REPLACE FUNCTION drop_table_if_exists(text, bool) RETURNS bool
AS '
DECLARE
opt text;
rec record;
BEGIN
IF $2 THEN
opt := '' CASCADE'';
ELSE
opt := '''';
END IF;
SELECT INTO rec oid FROM pg_class WHERE relname = $1::name;
IF FOUND THEN
EXECUTE ''DROP TABLE '' || $1 || opt;
RETURN true;
END IF;
RETURN false;
END;
' LANGUAGE 'plpgsql';
regression=# SELECT drop_table_if_exists('foo', false);
drop_table_if_exists
----------------------
t
(1 row)
regression=# SELECT drop_table_if_exists('foo', false);
drop_table_if_exists
----------------------
f
(1 row)
HTH,
Joe
From | Date | Subject | |
---|---|---|---|
Next Message | Andrew McMillan | 2003-03-15 07:57:12 | Re: SERIAL does not ROLLBACK |
Previous Message | Josh Berkus | 2003-03-14 16:59:39 | Re: get the oid |