我正在尝试将变量用作存储过程中的表名,并且它将其用作字符串文字而不是实际的表名。为什么是这样?还有另一种方法我应该这样做(除了在PHP中这样做)?
DROP PROCEDURE IF EXISTS settonull;
DELIMITER //
CREATE PROCEDURE settonull()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE _tablename VARCHAR(255);
DECLARE _columnname VARCHAR(255);
DECLARE cur1 CURSOR FOR SELECT CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS table_name, COLUMN_NAME AS column_name FROM information_schema.COLUMNS WHERE IS_NULLABLE = 'YES' AND TABLE_SCHEMA = 'blip_notify' AND table_name = 'notify_queue' LIMIT 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO _tablename, _columnname;
IF done THEN
LEAVE read_loop;
END IF;
UPDATE _tablename SET _columnname = NULL WHERE LENGTH(TRIM(_columnname)) = 0;
END LOOP;
CLOSE cur1;
END//
DELIMITER ;
CALL settonull();
输出:
0 row(s) affected, 1 warning(s)
Execution Time : 0 sec
Transfer Time : 1.094 sec
Total Time : 1.095 sec
Note Code : 1305
PROCEDURE settonull does not exist
---------------------------------------------------
0 row(s) affected
Execution Time : 0.002 sec
Transfer Time : 1.011 sec
Total Time : 1.014 sec
---------------------------------------------------
Query: call settonull()
Error Code: 1146
Table 'blip_notify._tablename' doesn't exist
Execution Time : 0 sec
Transfer Time : 0 sec
Total Time : 0.003 sec
---------------------------------------------------
答案 0 :(得分:6)
您需要使用动态sql。你好啊。
SET @s = CONCAT('UPDATE ', _tablename, ' SET ', _columnname, ' = NULL WHERE LENGTH(TRIM(', _columnname, ')) = 0' );
PREPARE stmt FROM @s;
EXECUTE stmt;
答案 1 :(得分:3)
变量包含字符串值(或其他数据类型),而不是表标识符。
如果将SQL查询的各个部分作为字符串连接在一起,然后将PREPARE and EXECUTE该字符串作为SQL语句连接,则可以在存储过程中执行所需的操作。
但是FWIW,我会用PHP做的。
在向SQL查询中动态添加表名时,请注意SQL注入漏洞,因为像mysql_real_escape_string()这样的转义函数对表名没有帮助。请参阅我的演示文稿SQL Injection Myths and Fallacies中的“白名单地图”解决方案。