我想使用for循环将100到9999之间的数字添加到表中。我尝试了以下查询:
DELIMITER //
BEGIN
FOR phone_number IN 100..9999 LOOP
INSERT INTO phones (`phoneid`,`phone`,`active`) VALUES (NULL, phone_number, "1");
END LOOP;
END
//
我收到以下错误
1064 - 您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以获得正确的语法,使用在'附近的电话号码IN 100..9999 LOOP INSERT INTO手机(第2行`ph'
有什么问题?
答案 0 :(得分:1)
我不认为mysql存在" for循环"。你可以用这个:
DELIMITER //
DROP PROCEDURE IF EXISTS ins//
CREATE PROCEDURE ins()
BEGIN
DECLARE cnt INT;
SET cnt=100;
WHILE cnt<10000 DO
INSERT INTO phones (`phoneid`,`phone`,`active`) VALUES (NULL, cnt, "1");
SET cnt=cnt+1;
END WHILE;
END//
DELIMITER ;
CALL ins();
答案 1 :(得分:0)
即使没有存储代码,您也可以生成所需的值,例如:
INSERT INTO phones (
`phoneid`,
`phone`,
`active`
)
SELECT
NULL,
n0.n+10*n1.n+100*n2.n+1000*n3.n AS num,
"1"
FROM
(SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS n0
CROSS JOIN
(SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS n1
CROSS JOIN
(SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS n2
CROSS JOIN
(SELECT 0 AS n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS n3
HAVING
num>99
这些CROSS JOIN
会生成值0..9999
,因此您必须过滤那些低于100
的值(这就是为什么它有HAVING
子句)