我正在尝试在MySQL中编写一个存储过程作为清理程序,它将用于从表中删除数据(所有表的一个存储过程)
CREATE PROCEDURE `cleaner`(
IN table_name_in varchar(255),
IN field_name_in varchar(255),
IN day_in int
)
BEGIN
DECLARE FoundCount INT;
SELECT COUNT(1) INTO FoundCount
FROM table_name_in where STR_TO_DATE(field_name_in, "%Y-%m-%d") < STR_TO_DATE(NOW() - INTERVAL day_in DAY, "%Y-%m-%d");
IF FoundCount = 1 THEN
SET SQL_SAFE_UPDATES = 0;
DELETE from table_name_in where STR_TO_DATE(field_name_in, "%Y-%m-%d") < STR_TO_DATE(NOW()- INTERVAL day_in DAY, "%Y-%m-%d");
SET SQL_SAFE_UPDATES = 1;
select "true" as isDeleted , "true" as isValuePresent ;
else
select "false" as isDeleted , "false" as isValuePresent ;
END IF;
END
我将其称为
call cleaner('employee','created_on',30)
表示使用字段created_on
删除员工表中所有30天以上的记录但它给我一条错误信息
Error Code: 1146. Table 'table_name_in' doesn't exist
作为员工表存在,但不将员工作为参数
答案 0 :(得分:1)
这对我有用
CREATE PROCEDURE `cleaner`(
IN table_name_in varchar(255),
IN field_name_in varchar(255),
IN day_in int
)
BEGIN
SET SQL_SAFE_UPDATES = 0;
SET @sql = CONCAT('DELETE FROM ',table_name_in,' WHERE STR_TO_DATE(',field_name_in,', "%Y-%m-%d") < STR_TO_DATE(NOW() - INTERVAL ',day_in,' DAY, "%Y-%m-%d")');
PREPARE s1 from @sql;
EXECUTE s1;
SET SQL_SAFE_UPDATES = 1;
END
资料来源:Mysql stored procedure don't take table name as parameter