CONCATENATED INSERT不接受WHERE子句

时间:2012-10-06 16:19:34

标签: mysql sql stored-procedures insert

这让我非常难过。我有一个看起来像这样的MySQL存储过程。

 DELIMITER $$

CREATE PROCEDURE `lms`.`leads_to_bak` ()
BEGIN
SET @table1 = (SELECT `tabler_name` FROM `sets` WHERE `on_off`=0 LIMIT 1);
SET @table2 = CONCAT(@table1, '_bak');
SET @SQL1 = CONCAT('INSERT INTO ',@table2, '(', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), 'lead_id,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table2), ')', ' SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), 'lead_id,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table1), ' FROM ', @table1);
PREPARE stmt FROM @sql1;
EXECUTE stmt;
END$$

DELIMITER ;

现在重要的部分就是:

SET @SQL1 = CONCAT('INSERT INTO ',@table2, '(', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), 'lead_id,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table2), ')', ' SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), 'lead_id,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table1), ' FROM ', @table1);

现在从它的外观来看,该陈述可以翻译为

INSERT INTO @table2 (col1, col2, col3, ...)[minus lead_id] SELECT (col1, col2, col3, ...)[minus lead_id] FROM @table1

非常简单吧?好吧,我试图在WHERE语句的末尾附加一个INSERT子句,使其看起来像这样:

INSERT INTO @table2 (col1, col2, col3, ...) SELECT (col1, col2, col3, ...) FROM @table1 WHERE set_id = (SELECT set_id FROM sets WHERE on_off = 0);

但没有骰子。错误很多。哎,我甚至尝试过:

INSERT INTO (col1, col2, col3, ...) SELECT (col1, col2, col3, ...) FROM @table1 WHERE set_id = 1;

字符串输出为:

INSERT INTO leads_auto_bak(set_id,new_old,upload_date,agent,vendors,callcenter,generation_date,first_name,last_name,email,phone,address,city,state,zip,dob,gender,marital_status,rented,year,make,model,trim,vin,primary_use,miles_oneway,mileage,license_num,license_state,education,job_title,license_status) SELECT set_id,new_old,upload_date,agent,vendors,callcenter,generation_date,first_name,last_name,email,phone,address,city,state,zip,dob,gender,marital_status,rented,year,make,model,trim,vin,primary_use,miles_oneway,mileage,license_num,license_state,education,job_title,license_status FROM leads_auto

但仍然没有。我在最后用CONCAT那条线路的不同方式玩弄它但它不会让步。有人有建议吗?

1 个答案:

答案 0 :(得分:0)

您缺少要插入的表名:

INSERT INTO MYTABLE (col1, col2, col3) 
SELECT col1, col2, col3
FROM @table1 
WHERE ...

另外,请注意SELECT子句中的列周围不应有括号。