Re: Re: Re: Test for existence of Table

From: Ed Loehr <eloehr(at)austin(dot)rr(dot)com>
To: Gregory Wood <gregw(at)com-stock(dot)com>
Cc: "Craig L(dot) Ching" <cching(at)mqsoftware(dot)com>, PostgreSQL-General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Re: Re: Test for existence of Table
Date: 2001-01-05 19:20:26
Message-ID: 3A561E7A.2427E623@austin.rr.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Gregory Wood wrote:
>
> What would be nice is if there were a way to only DROP a table if it exists.
> But I would consider this to be rather low priority.

This might help...

CREATE FUNCTION table_exists(TEXT) RETURNS BOOLEAN AS
'DECLARE
tablename ALIAS FOR $1;
temp RECORD;
BEGIN
SELECT INTO temp *
FROM pg_class c
WHERE c.relname = tablename
AND c.relkind = ''r'';

if found then
return ''t''::BOOLEAN;
else
return ''f''::BOOLEAN;
end if;
END;'
LANGUAGE 'plpgsql';

-- test table
CREATE TABLE realtable (id INTEGER);

-- test example
SELECT table_exists('realtable'::TEXT);
SELECT table_exists('faketable'::TEXT);

-- clean up
DROP TABLE realtable;
DROP FUNCTION table_exists(TEXT);

It'd be even nicer if you could drop the table from within the PL/pgSQL
function, but I found that does not work in 7.0.0.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Andy 2001-01-05 19:20:54 Postgres 7.03 table describe problem
Previous Message Tom Lane 2001-01-05 18:56:00 Re: Another 7.1 EXECUTE Question