我正在尝试使用mysql遍历我的数据库,并将字符串转换为只有数字和。以便将该列从varchar转换为float。然而,当我调用存储过程时,它实际上似乎并没有改变datatable。我希望有人能帮我找出问题所在?
use mydb;
SET GLOBAL log_bin_trust_function_creators = 1;
CREATE TABLE IF NOT EXISTS `docs` (
`id` int(6) unsigned NOT NULL,
`rev` int(3) unsigned NOT NULL,
`content` varchar(200) NOT NULL,
PRIMARY KEY (`id`,`rev`)
) DEFAULT CHARSET=utf8;
-- INSERT INTO `-- docs` (`id`, `rev`, `content`) VALUES
-- ('1', '1', '0.0 '),
-- ('2', '1', '2,765'),
-- ('3', '1', '*'),
-- ('4', '1', '0.7665');
DROP FUNCTION IF EXISTS floatify;
DELIMITER //
CREATE FUNCTION floatify(str VARCHAR(200)) RETURNS VARCHAR(16)
BEGIN
DECLARE i, len SMALLINT DEFAULT 1;
DECLARE ret VARCHAR(16) DEFAULT '';
DECLARE c CHAR(1);
SET len = CHAR_LENGTH( str );
REPEAT
BEGIN
SET c = MID( str, i, 1 );
IF c REGEXP '[0-9|.]' THEN
SET ret=CONCAT(ret,c);
END IF;
SET i = i + 1;
END;
UNTIL i > len END REPEAT;
RETURN ret;
END//
DELIMITER ;
DROP PROCEDURE IF EXISTS tofloat;
DELIMITER //
CREATE PROCEDURE tofloat()
BEGIN
DECLARE currentid INT DEFAULT 1;
DECLARE RowCnt BIGINT DEFAULT 0;
SELECT RowCnt = COUNT(*) FROM docs;
WHILE currentid <= RowCnt DO
UPDATE docs
SET content = floatify(content)
WHERE id = currentid;
SET currentid = currentid + 1 ;
END WHILE;
-- ALTER TABLE docs
-- MODIFY content FLOAT NOT NULL DEFAULT 0 ;
END//
DELIMITER ;
-- select * from docs;
CALL tofloat();
select * from docs;
2条答案
按热度按时间nmpmafwu1#
设置rowcnt=(从文档中选择count(*));修复了这个问题,您可以将变量设置为过程中子查询的结果。
eqfvzcg82#
让sql完成这项工作: