Re: Checking for table existence
| От | Josh Berkus | 
|---|---|
| Тема | Re: Checking for table existence | 
| Дата | |
| Msg-id | web-120865@davinci.ethosmedia.com обсуждение исходный текст | 
| Ответ на | Checking for table existence ("Julester" <cubalibr@optonline.net>) | 
| Ответы | Re: Checking for table existence | 
| Список | 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@agliodbs.com
   and data management solutions       (415) 565-7293
  for law firms, small businesses        fax 621-2533
    and non-profit organizations.      San Francisco
		
	Вложения
В списке pgsql-sql по дате отправления: