Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Check if table exists error

Tags:

mysql

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

like image 880
Resitive Avatar asked Dec 10 '12 10:12

Resitive


2 Answers

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

like image 124
David Martin Avatar answered Nov 15 '22 15:11

David Martin


Try this:

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

OR

CREATE TABLE IF NOT EXISTS 'TableName'
like image 7
Saharsh Shah Avatar answered Nov 15 '22 15:11

Saharsh Shah