Is there a portable way of determining if a database table already exists or not?
问题:
回答1:
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.
回答2:
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.
回答3:
I would say
select 'x' from <table_name> where 0=1;
The drawback is that if you get an error, you don't know for sure what was the real cause. It might be missing table or e.g. a connection error. You can parse the error message, but definitely it would not be portable.
回答4:
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
回答5:
Here is something that is reasonably portable:
select now() from TABLE limit 1;
It doesn't rely on knowledge of any particular column.
It doesn't incur the overhead that count(*) sometimes has.
It doesn't matter whether the table is empty or not.
It fails if the table doesn't exist.
回答6:
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
回答7:
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.