Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Mysql Loop Error

hello world loop mysql

  • Please log in to reply
5 replies to this topic

#1 johnP

johnP

    CC Newcomer

  • Member
  • PipPip
  • 21 posts

Posted 01 June 2012 - 04:37 AM

Hello,
I have a problem with my sql loop.

Here is my code:

BEGIN  
DECLARE @id INT;  
DECLARE @count INT;  
SET @id = 1;  
SET @count = 0;  

WHILE (@count < @id) DO  
   INSERT INTO members (id, description) VALUES ((@id+1), 'Hello World');  
   SET @count = (@count+1);  
END WHILE;  
END;  

I have this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE @id INT' at line 2
After I have also an error in the loop.

Do you have an idea of ​​the errors?

Thank you.
  • 0

#2 serpent

serpent

    CC Regular

  • Member
  • PipPipPip
  • 30 posts
  • Programming Language:C++, PHP

Posted 03 June 2012 - 07:08 AM

I'm not sure, but I think that local variables should not be prefixed with @.
  • 0

#3 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts
  • Location:Argentina
  • Programming Language:C, C++, C#, PHP, JavaScript, Transact-SQL, Bash, Others
  • Learning:Java, Others

Posted 03 June 2012 - 11:23 AM

you don't need the @ in mysql local vars
  • 0

#4 johnP

johnP

    CC Newcomer

  • Member
  • PipPip
  • 21 posts

Posted 04 June 2012 - 09:08 AM

When remove the @, it displays this error:

#1193 - Unknown system variable 'id'


My new code is here:

SET id = 1; 
SET count = 0; 
WHILE (count < id) DO 
   INSERT INTO members (id, description) VALUES ((id+1), 'Hello World'); 
   SET count = (count+1); 
END WHILE; 

  • 0

#5 serpent

serpent

    CC Regular

  • Member
  • PipPipPip
  • 30 posts
  • Programming Language:C++, PHP

Posted 05 June 2012 - 07:15 AM

You need to declare your local vars
DECLARE id INT;
DECLARE count INT;

  • 0

#6 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts
  • Location:Argentina
  • Programming Language:C, C++, C#, PHP, JavaScript, Transact-SQL, Bash, Others
  • Learning:Java, Others

Posted 05 June 2012 - 12:40 PM

exactly !

take a look at this example, remember always that your declares must be inside a begin-end

http://www.kbedell.c...-uses-a-cursor/
  • 0





Also tagged with one or more of these keywords: hello world, loop, mysql

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download