MYSQL - 使用while循环更新

时间:2012-03-28 20:40:50

标签: mysql

declare c int 
set c = 1
while c<700 do
update users set profile_display_name = concat(substring(first_name,1,1), last_name) 
        where profile_display_name is null and id between ((c-1)*10000+1) and (c*10000);
SET c = c+1;
End while ;

我收到错误。接近声明和结束时声明。我在哪里弄错了?

3 个答案:

答案 0 :(得分:3)

以下是如何将其定义为存储过程:

DELIMITER $$
CREATE PROCEDURE proc_name()
BEGIN

    DECLARE c int ;                      --- added ;
    SET c = 1 ;                          --- added ;
    WHILE c<700 DO
      UPDATE users 
        SET profile_display_name = concat(substring(first_name,1,1), last_name) 
        WHERE profile_display_name IS NULL
          AND id BETWEEN ((c-1)*10000+1) AND (c*10000);
      SET c = c + 1 ;
    END WHILE ;

END $$
DELIMITER ;

答案 1 :(得分:3)

这对我来说效果更好

DELIMITER $$

CREATE DEFINER=`ops`@`localhost` PROCEDURE `myproc`()
BEGIN
DECLARE c INT;
SET c = 1;
WHILE c < 700 DO 
SELECT CONCAT('Loop #:', c) ;

update users 
set profile_display_name = concat(substring(first_name,1,1), last_name) 
where (profile_display_name is null or profile_display_name = '')
and id between ((c-1)*10000+1) and (c*10000); 

commit;

SET c=c+1; 

END WHILE;
END

答案 2 :(得分:1)

在MySQL中,复合语句和流控制结构只能用于存储的例程 - MySQL Compound-Statement Syntax