1

这让我很困惑。我有一个看起来像这样的 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这条线,但它不会让步。有人给点建议吗?

4

1 回答 1

0

您缺少要插入的表名:

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

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

于 2012-10-06T16:21:20.407 回答