Question

En utilisant uniquement MySQL , je vois s'il est possible d'exécuter une instruction insert UNIQUEMENT si la table est nouvelle. J'ai créé avec succès une variable utilisateur pour voir si la table existe. Le problème est que vous ne pouvez pas utiliser " WHERE " avec une déclaration insert. Des idées sur la façon de faire fonctionner cela?

// 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;
Était-ce utile?

La solution

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

Autres conseils

Utilisez une instruction if à la place de la clause where:

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top