Check if a SQL table exists

后端 未结 9 2350
北海茫月
北海茫月 2020-12-01 06:30

What\'s the best way to check if a table exists in a Sql database in a database independant way?

I came up with:

   bool exists;
   const string sql         


        
9条回答
  •  时光说笑
    2020-12-01 06:38

    If you're trying for database independence you will have to assume a minimum standard. IIRC The ANSI INFORMATION_SCHEMA views are required for ODBC conformance, so you could query against them like:

    select count (*) 
      from information_schema.tables 
     where table_name = 'foobar'
    

    Given that you are using ODBC, you can also use various ODBC API calls to retrieve this metadata as well.

    Bear in mind that portability equates to write-once test anywhere so you are still going to have to test the application on every platform you intend to support. This means that you are inherently limited to a finite number of possible database platforms as you only have so much resource for testing.

    The upshot is that you need to find a lowest common denominator for your application (which is quite a lot harder than it looks for SQL) or build a platform-dependent section where the non-portable functions can be plugged in on a per-platform basis.

提交回复
热议问题