A simulated atomic counter without the need to set variables within expressions can be achieved with
repeat
select value + 1 into @value from cnt where id = 1;
update cnt set value = @value where id = 1 and value = @value - 1;
until (select row_count()) > 0 end repeat;
This is not actually atomic (as a different session can increase the counter between select
and update
), but it will only update if that didn't happen, otherwise it will retry (potentially indefinitely if you have a really really busy counter). row_count()
is used to check if that update happened.
There is no "new syntax" for that deprecated feature - it will, intentionally, not be possible anymore to do this in MySQL 9 (thus the warning), see the change log. The main use case for setting user variables within expressions was simulating CTEs (for example a recursive hierarchical query or the rank()
window-function), and with the support of CTEs in MySQL 8, it was possible to deprecate this functionality.
For context, the intended behaviour of your syntax is to make
UPDATE cnt SET value = value + 1 where id = 1;
SELECT value INTO @val from cnt where id = 1;
behave atomically.
Obviously, the expected way to achieve this is to use a transaction, so there won't be a new syntax to replace your behaviour, like it was required for CTEs; you may however want to check if the reason you cannot use a transaction might be gone in a newer MySQL version (with potentially new capabilities).