Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a table exists, and if not, create it

Tags:

c#

mysql

odbc

I'm using a Odbc connection to a mysql server, and was wondering how I would go about checking if a table exists within my database, and if not, create it.

like image 801
Matt Avatar asked Apr 14 '10 04:04

Matt


1 Answers

Use CREATE TABLE IF NOT EXISTS.

UPDATE

For the record, not all RDBMSs support CREATE ... IF NOT EXISTS. MySQL does, but for those looking for a more portable solution, know that you have multiple (less efficient but otherwise functional) ways of achieving the same thing:

  • unconditionally issue CREATE TABLE; the statement will fail if the table already exists, in which case simply swallow the error and continue
  • SELECT from the tables object in the ANSI information_schema to see whether or not a given table already exists (as originally suggested by @Derek -- see @lexu's answer for the actual query); depending on the result, either issue CREATE TABLE -- or do not (when accessing information_schema.tables beware of issues such as table name case sensitivity, the possibility of your table appearing in multiple schemas, etc.)
like image 165
vladr Avatar answered Sep 30 '22 05:09

vladr