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
zajca
  • 2,288
  • 4
  • 30
  • 40

1 Answers1

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
wchiquito
  • 16,177
  • 2
  • 34
  • 45
  • 1
    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: http://stackoverflow.com/a/1010042/ – Aziz Shaikh Dec 03 '13 at 14:55
  • @AzizShaikh: That's right, so it initializes the variable `@variable` in each execution of the stored procedure. See `(SELECT @variable := 0) init` – wchiquito Dec 03 '13 at 15:43
  • 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? – Martin Asenov Jun 27 '14 at 21:05