SQL - How to make a conditional INSERT

Using only MySQL , I see if it is possible to run the insert statement ONLY if the table is new. I successfully created a user variable to see if the table exists. The problem is that you cannot use "WHERE" with the insert statement. Any ideas on how to do this?

// See if the "country" table exists -- saving the result to a variable
SELECT
    @table_exists := COUNT(*)
FROM
    information_schema.TABLES
WHERE
    TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'country';

// Create the table if it doesn't exist
CREATE TABLE IF NOT EXISTS country (
    id INT unsigned auto_increment primary key,
    name VARCHAR(64)
);

// Insert data into the table if @table_exists > 0
INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands') WHERE 0 < @table_exists;
+5
source share
2 answers
IF @TableExists > 0 THEN
   BEGIN
       INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands');
   END
+6
source

Use the if statement instead of the where clause:

http://dev.mysql.com/doc/refman/5.0/en/if-statement.html

+2
source

All Articles