5

I'm trying to check if a table already exists, however I can't get this working.

IF EXISTS (SELECT 1 
    FROM sysobjects 
    WHERE xtype='u' AND name='tablename') 
        SELECT 'table already exists.' 
ELSE 
BEGIN
     CREATE TABLE Week_(
             id INT(10)AUTO_INCREMENT PRIMARY KEY (id),
             ...
             ...)
             END; 

My error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS (SELECT 1 FROM sysobjects WHERE xtype='u' AND name' at line 1

Can someone help me with this?

Thanks in advance

2
  • sysobjects, xtype='u'? Looks like you are using MS Sql Server. Commented Dec 10, 2012 at 11:12
  • aha, so that's why it didn't work ;) I'm using MySQL, found this code somewhere on the internet. Commented Dec 10, 2012 at 13:42

2 Answers 2

19

In MySQL you can use the following syntax:

CREATE TABLE IF NOT EXISTS

http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Sign up to request clarification or add additional context in comments.

Comments

7

Try this:

SELECT * 
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'DBName' AND TABLE_NAME = 'TableName'

OR

CREATE TABLE IF NOT EXISTS 'TableName'

1 Comment

Note: the Select from information_schema.TABLES does not work in very early version of MySQL (e.g 4.1) as they didn't have those tables

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.