如何在循环中执行此 MySql 语句

How can I perform this MySql Statement in a loop

我会更复杂地编写我的 cmd 行语句。如何使用循环来完成?

     update refs set custom_7 = '';
     update refs set custom_7='1' where custom_7 = '' limit 220 ;
     update refs set custom_7='2' where custom_7 = '' limit 220 ;
     update refs set custom_7='3' where custom_7 = '' limit 220 ;
     ...
     update refs set custom_7='100' where custom_7 = '' limit 220 ;

非常感谢。

你可以这样试试(请把datatype(length)换成custom7的类型)

DECLARE @count INT;    
SET @count = 1;        
WHILE @count<= 100    
     BEGIN
   
          UPDATE refs SET custom_7 = CAST(@count AS **datatype(length)**) WHERE custom_7 = '' LIMIT 220;    
          SET @count = @count + 1;    
     END;

如果有一个列,如 id,定义了您要更新行所依据的行的顺序,请使用 ROW_NUMBER() window 函数对行并加入 table:

WITH cte AS (SELECT *, ROW_NUMBER() OVER (ORDER BY id) rn FROM refs)
UPDATE refs r
INNER JOIN cte c ON c.id = r.id
SET r.custom_7 = (c.rn - 1) DIV 220 + 1
WHERE c.rn <= 100 * 220; -- remove the WHERE clause if there is actually no limit to the values of custom_7

如果没有像 id 这样的列,您可以从 ROW_NUMBER()OVER() 子句中删除 ORDER BY id,但随后行将被任意更新。

查看简化版 demo.