2008-11-15 55 views
5

Usando solo MySQL, estoy viendo si es posible ejecutar una instrucción de inserción SÓLO si la tabla es nueva. Creé con éxito una variable de usuario para ver si existe la tabla. El problema es que no puede usar "DONDE" junto con una instrucción de inserción. ¿Alguna idea sobre cómo hacer que esto funcione?SQL - Cómo hacer un INSERT condicional

// 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; 

Respuesta

6
IF @TableExists > 0 THEN 
    BEGIN 
     INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands'); 
    END