我正在尝试更新数据库中每个表中一列的所有行。我当前的SQL如下所示:
SELECT CONCAT('UPDATE `', a.table_name, '` SET columnName = NULL;')
FROM information_schema.tables a
WHERE a.table_schema = 'databaseName'
当我运行此命令时,我得到一系列正在运行的命令,例如:
UPDATE `Friday` SET columnName = NULL;
星期五是我指定的数据库中的表之一。问题是,当我运行此命令时,表本身未更改。如果我采用我的连接输出的命令之一并运行它,那么该表将受到影响。我对使用MySQL有点陌生,所以为什么一系列串联命令与单个命令运行会改变效果?我的初始命令格式是否与我要实现的格式不正确?感谢您的帮助!
编辑:在发表评论和文档之后,这是我所处位置的更新。
SET @s:='';
SELECT @s:=concat(@s, 'UPDATE TABLE ', a.TABLE_SCHEMA,'.`', a.TABLE_NAME, '` SET columnName = NULL;') FROM INFORMATION_SCHEMA.TABLES a where table_schema = 'databaseName';
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
只需仔细阅读文档,便会发现准备好的语句不适用于多个语句。调查程序。
编辑:
这与我要完成的目标有点接近。尽管如此,还是有一些我需要解决的错误。
DELIMITER $$
DROP PROCEDURE IF EXISTS myproc $$
CREATE PROCEDURE myproc()
NOT DETERMINISTIC
MODIFIES SQL DATA
BEGIN
DECLARE done tinyint(1) DEFAULT FALSE;
DECLARE sql2 VARCHAR(2000);
DECLARE csr CURSOR FOR
SELECT CONCAT('UPDATE `',c.table_schema,'`.`',c.table_name,'` SET `columnName` = NULL') AS sql2
FROM information_schema.columns c
WHERE c.column_name = 'columnName'
AND c.table_schema IN ('databaseName');
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN csr;
do_foo: LOOP
FETCH csr INTO sql2;
IF done THEN
LEAVE do_foo;
END IF;
PREPARE stmt FROM sql2;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP do_foo;
CLOSE csr;
END$$
DELIMITER ;
答案 0 :(得分:0)
这是我想出的解决方案。感谢那些发表评论并指出我正确方向的人。如果将来有人需要更新数据库中的每一列,这就是我所做的:
DELIMITER $$
DROP PROCEDURE IF EXISTS myproc $$
CREATE PROCEDURE myproc()
NOT DETERMINISTIC
MODIFIES SQL DATA
BEGIN
DECLARE done tinyint(1) DEFAULT FALSE;
DECLARE sql2 VARCHAR(2000);
DECLARE csr CURSOR FOR
SELECT CONCAT('UPDATE ',c.table_schema,'.`',c.table_name,'` SET columnName = NULL') AS sql2
FROM information_schema.columns c
WHERE c.column_name = 'columnName'
AND c.table_schema IN ('databaseName');
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN csr;
do_foo: LOOP
FETCH csr INTO sql2;
IF done THEN
LEAVE do_foo;
END IF;
SET @newTest = sql2;
PREPARE stmt FROM @newTest;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP do_foo;
CLOSE csr;
END$$
DELIMITER ;