2008-11-15 8 views
5

En utilisant seulement MySQL, je vois si c'est possible d'exécuter une instruction d'insertion SEULEMENT si la table est nouvelle. J'ai réussi à créer une variable utilisateur pour voir si la table existe. Le problème est que vous ne pouvez pas utiliser "WHERE" avec une instruction d'insertion. Des idées sur comment faire fonctionner cela?SQL - Comment faire un INSERT conditionnel

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

Répondre

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