views:

320

answers:

5

Is there a portable way of determining if a database table already exists or not?

+4  A: 

This is as portable as it gets, sadly:

select
    count(*)
from
    information_schema.tables
where
    table_name = 'tablename'
    and table_schema = 'dbo'

This definitely works on SQL Server, MySQL, and Postgres. Not so much on Oracle, though. You'd have to access the Oracle data dictionary for that. However, there is an open source project that creates information_schema in Oracle from the data dictionary. You can try that if you need absolute portability.

P.S.-Schema doesn't have to be dbo, but that's the most common.

Eric
don't forget to check for schema too. dbo.tablename and MySchema.tablename could both exist.
Scott Ivey
+1  A: 

Portable? I don't think so.

Maybe the closest you can get is:

select * from <table>

And this would return an error if the table doesn't exist.

Alan
Aye Alan, thats the conclusion I came to. Lame!
jkp
A: 

As every DBMS has its own metabase, I think the most "portable" way to do this is using the application caller itself. Something like

try
    execute("select top 1 * from table")
    return (true)
catch
    return false
Rodrigo
I'm not sure `top` is portable though.
jkp
well, if even top 1 is not absolutely portable enough, just use select *
Rodrigo
A: 

Attempt to query the table. If the query fails -- you get an error, it doesn't exist.

That is probably as portable as you can get. The burden of producing the result then depends on the code querying the table/database.

select top 1 *
from MyTable

Keep the query as simple as possible to prevent other possible errors.

Frank V
A: 

The INFORMATION_SCHEMA views are ANSI standard - so those should be your most portable option. Don't forget to add the schema and table type to your where clause...

if exists(select  *
          from    information_schema.tables
          where   table_schema = 'dbo'
                  and table_name = 'MyTable'
                  and table_type = 'basetable')
begin
     -- your code here
end
Scott Ivey