2008-11-15 62 views
5

只使用MySQL,我看到如果可能運行一個插入語句只有當表是新的。我成功創建了一個用戶變量來查看錶是否存在。問題是你不能使用「WHERE」和插入語句。任何想法如何得到這個工作?SQL - 如何使條件INSERT

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

回答

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