3
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 ;

I am getting error. near declare and end while statement. Where am I making mistake??

7
  • I tried, I am from SQL background. I couldn't guess anything. Any advise? Commented Mar 28, 2012 at 20:51
  • What version of MySQL are you using? Commented Mar 28, 2012 at 20:58
  • Is this code, part of a trigger or a stored procedure? What error do you get? Commented Mar 28, 2012 at 21:07
  • You probably need ; after each statement: declare c int; set c=1; Commented Mar 28, 2012 at 21:10
  • 1
    You haven't answered @ypercube's previous question. Is this code part of a stored routine? Commented Mar 28, 2012 at 21:18

3 Answers 3

7

This Works much better for me

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
Sign up to request clarification or add additional context in comments.

1 Comment

Why you need commit there?
3

Here's how it would be defined as a stored procedure:

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 Comment

Nicely done. One addition actually helped me more is a COMMIT statement before SET c=c+1;
1

In MySQL compound statements and flow control structures can only be used in stored routines - MySQL Compound-Statement Syntax

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.