【发布时间】:2019-06-28 14:29:32
【问题描述】:
我认为我在下面的 mysql 脚本中编写 WHILE 语句时做错了。我已经测试了以下代码的每个单独组件,并且一切都独立工作(没有抛出的错误测试输出符合预期),除了 WHILE(抛出错误并且只输入 NULL 值并且只经历一次循环迭代)。我正在遵循https://dev.mysql.com/doc/refman/5.7/en/while.html 记录的说明,但我似乎遗漏了一些东西。我想要做的是在这个表中插入几条记录(数百万)。我究竟做错了什么?为什么这个 WHILE 语句不循环,为什么只插入 NULL 值?
来源
USE wordpress;
SET @i := 0;
WHILE @i < 10 DO
SET @rand_value = CAST(FLOOR(RAND()*10000) as CHAR);
SELECT @rand_value as CONCAT('rand_value at ', CAST(@i as CHAR));
INSERT INTO wp_wpdatatable_1 (jiraissue, assignee, testcasename, description, image, automation, testresult, date, status, priority, os, testtype, location, flavor)
VALUES
(CONCAT('TEST ISSUE ', @rand_value)
, CONCAT('ASSIGNEE ', @rand_value)
, CONCAT('TEST CASE NAME ', @rand_value)
, CONCAT('DESCRIPTION ', @rand_value)
, CONCAT('IMAGE ', @rand_value)
, CONCAT('AUTOMATION ', @rand_value)
, CONCAT('TESTRESULT ', @rand_value)
, CONCAT('DATE ', @rand_value)
, CONCAT('STATUS ', @rand_value)
, CONCAT('PRIORITY ', @rand_value)
, CONCAT('OS ', @rand_value)
, CONCAT('TESTTYPE ', @rand_value)
, CONCAT('LOCATION ', @rand_value)
, CONCAT('FLAVOR ', @rand_value));
SET @i := @i + 1;
END WHILE;
输出
mysql> source /root/populate_wp_wpdatatable_1.sql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
Query OK, 0 rows affected (0.00 sec)
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHILE @i < 10 DO
SET @rand_value = CAST(FLOOR(RAND()*10000) as CHAR)' at line 1
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('rand_value at ', CAST(@i as CHAR))' at line 1
Query OK, 1 row affected (0.01 sec)
Query OK, 0 rows affected (0.00 sec)
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END WHILE' at line 1
奇怪的是,您可以在输出中看到“1 行受影响”。所以它实际上确实经历了 WHILE 循环的 ONE 迭代,但它只执行一次,并且只将 NULL 值放入表中。希望有人能发现我缺少的东西。提前致谢!
【问题讨论】:
-
WHILE语句只能在存储过程中使用。 -
我想我可以做一个 SP。有什么理由会这样吗?让这个 SP 插入几百万条记录会有问题吗?
-
控制语句如
WHILE和IF不是SQL 查询。 -
SP 插入它们与其他方式没有区别。
-
第一个
SELECT一般也是错误的。您不能在SELECT的AS部分放置表达式。
标签: mysql while-loop insert bulkinsert