我可以在不使用过程/函数的情况下在 MySQL 中运行循环吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14739940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I run a loop in MySQL without using a procedure/function?
提问by Mr. Boy
For testing, is it possible to run a loop from MySQL workbench or similar tool? I tried but got an error.
对于测试,是否可以从 MySQL 工作台或类似工具运行循环?我试过了,但出现错误。
If it is possible, please supply a simple example I can run.
如果可能,请提供一个我可以运行的简单示例。
采纳答案by Thanu
You can't do a for loop in an SQL editor without a stored procedure. I use TOAD for MySQL.
如果没有存储过程,就不能在 SQL 编辑器中执行 for 循环。我将TOAD 用于 MySQL。
A quick stored procedure should do the job:
一个快速的存储过程应该可以完成这项工作:
DELIMITER $$
DROP PROCEDURE IF EXISTS proc_loop_test$$
CREATE PROCEDURE proc_loop_test()
BEGIN
DECLARE int_val INT DEFAULT 0;
test_loop : LOOP
IF (int_val = 10) THEN
LEAVE test_loop;
END IF;
SET int_val = int_val +1;
SELECT int_val;
END LOOP;
END$$
DELIMITER ;
回答by Kache
There's a trick with limited use-cases that is "loop-like".
有一个“类似循环”的有限用例的技巧。
I wanted to create a large (1~2 million) row table of random integers for a test:
我想为测试创建一个大型(1~200 万)随机整数行表:
INSERT INTO test_table (num) VALUES(ROUND(RAND() * 1E6));
-- calling this will insert once for every row in test_table
INSERT INTO test_table (num)
SELECT ROUND(RAND() * 1E6)
FROM test_table;
So I quickly just kept doubling the number of rows until I had what I needed.
所以我很快就把行数加倍,直到我得到我需要的东西。
回答by Volker Raab
Supposed that you already have an arbitrary table myOldTable which is sufficiently long you could use the following trick:
假设您已经有一个足够长的任意表 myOldTable,您可以使用以下技巧:
set @counter = 0;
select (@counter := @counter+1), @counter*@counter from myOldTable limit 1000;
回答by Mike Lischke
If it is that you only want to block the current thread then use select sleep(seconds);
otherwise you can use a stored procedure (if there's something you want to loop over) or a UDF (user defined function).
如果您只想阻塞当前线程,则使用select sleep(seconds);
其他方式,否则您可以使用存储过程(如果您想要循环遍历)或 UDF(用户定义函数)。