Re: Checking for table existence

From: "Josh Berkus" <josh(at)agliodbs(dot)com>
To: "Julester" <cubalibr(at)optonline(dot)net>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Checking for table existence
Date: 2001-09-18 03:54:23
Message-ID: web-120865@davinci.ethosmedia.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Julester,

> Hi everyone. In my old SQL Server days, I used a command such as "IF
> exists(select name from sys_objects where name = 'xyztable')" to
> check if a
> table existed before creating it with a standard CREATE command. I
> looked
> in the PostgreSQL documentation, but for the life of me, I can't find
> an
> equivalent. I can view if the table exists by doing a select against
> the
> meta-data tables, but what about the IF statement ? Any help would
> be
> greatly appreciated. Thanks.

<grin> You've gotten a lot of complex answers to a simple question.
Confused yet?

If you're doing this in PL/pgSQL, you want a couple of functions:
(Hey Roberto, how about posting the 1st function on your site?)

CREATE FUNCTON table_exists(
VARCHAR ) RETURNS BOOLEAN AS '
DECLARE
t_name ALIAS for $1;
t_result VARCHAR;
BEGIN
--find table, case-insensitive
SELECT relname INTO t_result
FROM pg_class
WHERE relname ~* (''^'' || t_name || ''$'')
AND relkind = 'r';
IF t_result IS NULL THEN
RETURN FALSE;
ELSE
RETURN TRUE;
END IF;
END;'
LANGUAGE 'plpgsql';

... then you build your function around this:

CREATE FUNCTION my_function ( ...

...
IF NOT table_exists(''my_table'') THEN
CREATE TABLE ...
END IF;
...

Got the idea?

-Josh

______AGLIO DATABASE SOLUTIONS___________________________
Josh Berkus
Complete information technology josh(at)agliodbs(dot)com
and data management solutions (415) 565-7293
for law firms, small businesses fax 621-2533
and non-profit organizations. San Francisco

Attachment Content-Type Size
unknown_filename text/plain 2 bytes
unknown_filename text/plain 2 bytes
unknown_filename text/plain 2 bytes

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Diehl, Jeffrey 2001-09-18 07:07:47 Re: Out of free buffers... HELP!
Previous Message Kovacs Baldvin 2001-09-18 01:11:49 Re: Checking for table existence