0

I'm trying to get rank of user in the table with stored time.

RAW SQL query is working fine but I can't make it work as procedure.

SET @rownum := 0;
SELECT rank, user_id, best_time
FROM (
  SELECT @rownum := @rownum +1 AS rank,id, best_time, user_id
  FROM user_round WHERE round_id=1 ORDER BY best_time ASC
) AS result WHERE user_id = 1 

My try to procedure:

BEGIN
 DECLARE variable INT DEFAULT 0;
 SELECT rank,best_time, user_id
 FROM (
  SELECT SET variable=variable+1 AS rank, best_time, user_id
  FROM database.user_round WHERE round_id=1 ORDER BY best_time ASC
 ) AS result WHERE user_id = 1;
END
2
  • Try removing SET from SELECT SET variable=variable+1 Commented Dec 3, 2013 at 14:21
  • If i remove set I can save procedure but rank is always 0 Commented Dec 3, 2013 at 14:32

1 Answer 1

3

You need to continue using a 9.4. User-Defined Variables, not a 13.6.4.1. Local Variable DECLARE Syntax:

BEGIN
    -- DECLARE variable INT DEFAULT 0;
    SELECT rank, best_time, user_id
    FROM (
        -- SELECT SET variable = variable + 1 AS rank, best_time, user_id
        SELECT @variable := @variable + 1 AS rank, best_time, user_id
        FROM database.user_round, (SELECT @variable := 0) init
        WHERE round_id = 1
        ORDER BY best_time ASC
    ) AS result
    WHERE user_id = 1;
END
Sign up to request clarification or add additional context in comments.

3 Comments

In this case you may have to watch out for this: The difference between a procedure variable and a session variable is that procedure variable is reinitialized to NULL each time the procedure is called, while the session variable is not as mentioned at: stackoverflow.com/a/1010042
@AzizShaikh: That's right, so it initializes the variable @variable in each execution of the stored procedure. See (SELECT @variable := 0) init
why should we stick to user variables, since they would fail the query if the stored procedure is called simultaneously from two or more threads?

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.