Michael <
mic...@d3i.com> wrote:
> Is there a better solution than this?
There certainly is.
> CREATE PROCEDURE `get_tick_count`(p_user_id INT)
> DETERMINISTIC
^^^^^^^^^^^^^
This is wrong BTW.
> BEGIN
> START TRANSACTION;
>
> SELECT tick_count INTO @tick_count
> FROM user_tick_count
> WHERE user_id = p_user_id
> FOR UPDATE;
>
> SET @tick_count = @tick_count + 1;
>
> UPDATE user_tick_count
> SET tick_count = @tick_count
> WHERE user_id = p_user_id;
>
> SELECT @tick_count;
>
> COMMIT;
> END
No need to use a procedure. A single statement does the trick:
UPDATE user_tick_count
SET tick_count = (@my_tick_count:=tick_count+1)
WHERE user_id = p_user_id;
This will update the `tick_count` column in the `user_tick_count`
table with an atomic UPDATE and return the new value in the user
variable @my_tick_count.
You can then either SELECT the user variable to get the value into
your application
SELECT @my_tick_count;
or simply use the variable in subsequent SQL statements. This will
work for any engine (though for transactional engines you need an
additional COMMIT). User variables have session scope, so this is
safe for concurrent workload. RTFM on user variables.
XL