MySQL Stored Procedure with Insert Select and user variable

Dan picture Dan · Aug 10, 2013 · Viewed 12.3k times · Source

Problem: I have a MySQL stored procedure and I want to reset a user variable to 0 each time the procedure is called, but the variable seems to be remembering its value from each previous run and I cannot initialize it to zero.

Details: I have a data table (called data) which I read from and then generate records in a 1-to-1 correlation in another table (called results). I do this in a stored procedure that utilizes an Insert Select statement. I also use a user variable @mycount which increments with each row. Here is a simplified version of my code:

DELIMITER //
CREATE PROCEDURE doSomething
BEGIN
    SET @mycount := 0;
    INSERT INTO results (data_id, mycounter)
        SELECT data.id, (@mycount := @mycount+1)
        FROM data LEFT JOIN results ON data.id = results.data_id
        WHERE ... GROUP BY ...
        HAVING ...
        ORDER BY ...;
END //
DELIMITER ;

Analysis: This almost works as desired except I need @mycount to reset to zero each time it is run and the SET statement above is not achieving that. When debugging, I can see that the last value of @mycount is always remembered from the previous run of the stored procedure. I've also tried setting it to zero after the insert.

Notes:

  1. I am using a @ variable to increment and keep track of row number. Perhaps there is another option here?
  2. The problem seems related to the Having clause. When I run a similar but different query without the having clause, the variable resets no problem.

Question: Why can't I set @mycount to zero before running each time? If it IS resetting and it's just that my Having clause causes an unexpected count, is there some better way to rewrite my SQL?

I'm hoping someone has run into something similar, since this seems pretty obscure.

Answer

Ajay picture Ajay · Aug 11, 2013

I think you are using session variable(i.e; @mycount).Check below site you will get an answer

MySQL: @variable vs. variable. Whats the difference?