2

I have the following MySql script:

SET @skip = 0;
SET @max = (SELECT COUNT(*) FROM table1);

CREATE TEMPORARY TABLE TempTable(
   id INT NOT NULL,
   name VARCHAR(32) NOT NULL
);

loop1: LOOP
  INSERT INTO TempTable (id, name) SELECT id, name FROM table1 LIMIT @skip, 1;

  IF @skip < @max THEN
    SET @skip = @skip + 1;
    ITERATE loop1;
  END IF;
  LEAVE loop1;
END LOOP loop1;

SELECT * FROM TempTable;

This script is not working but it should select all the id and names in table1. I am using a loop because I am also going to do other stuff in those loops but that is for later. I am not looking for a solution like SELECT id, name FROM table1 but I want my error fixed. So I can continue with my loop.

The error I get is:

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 'loop1: LOOP INSERT INTO TempTable (id, name) SELECT id, name FROM table1' at line 1

1
  • I have no clue, I am trying to make this work, but I dont know for sure. Commented Sep 27, 2012 at 18:26

3 Answers 3

7
/* set delimiter */
DELIMITER $$

/* remove procedure if exists... */
DROP PROCEDURE IF EXISTS insert_it $$

/* create procedure */ 
CREATE PROCEDURE insert_it ()
BEGIN
DECLARE varcount INT DEFAULT 1;
DECLARE varmax INT DEFAULT 15;

WHILE varcount <= varmax DO
    INSERT INTO yourtable(fixed_val, count_val) VALUES(3493, varcount);
    SET varcount = varcount + 1;
END WHILE;

END $$

/* reset delimiter back to normal */
DELIMITER ;

/* call procedure */ 
CALL insert_it();
Sign up to request clarification or add additional context in comments.

2 Comments

Code only answers are usually frowned upon. Try adding an explination or code comments. Thanks.
While missing some explanation, I highly appreciated this A-Z solution - it worked out of the box.
6

try something like this for the syntax of your loop:

DECLARE @count INT;
DECLARE @max INT;
SET @count=1;
SET @max= (SELECT COUNT(*) FROM table1);
WHILE(@count < @max)
BEGIN
    /*your database query logic*/
END

use "SET @count=(@count+1)" to increment your counter within the loop

1 Comment

This is a good solution. Why do you explicitly use user variables here?
2

There is a syntax error in your code (the LIMIT @skip which is dynamic SQL and requires some tricks to make it work) but it is not at loop1: LOOP.

My guess is you are trying to use LOOP outside a compound statement (BEGIN ... END) like a stored procedure, which is not possible. You have to create a stored procedure to do that.

2 Comments

That would most certainly be the case, is a transaction also ok to use a loop in?
No, on dev.mysql.com/doc/refman/5.5/en/… it says: Stored procedures and functions, triggers, and events.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.