0

When I write code:

SET @code = 'a123';
UPDATE my_table SET number = (number + 1) WHERE code = @code;

it doesn't work correctly. But if I write code:

UPDATE my_table SET number = (number + 1) WHERE code = 'a123';

it works correctly. I want to use variable in "WHERE". how can I use it?

4
  • check this answer stackoverflow.com/questions/11754781/… Commented Jan 15, 2020 at 9:08
  • @Marwen Jaffel I check it but doesn't work again Commented Jan 15, 2020 at 9:19
  • Is your SET & UPDATE queries within same transaction? If it does not try to wrap them into START TRANSACTION; SET ...; UPDATE ...; COMMIT; Commented Jan 15, 2020 at 12:09
  • What do you mean under "it does not work"? Throws error? Not updating record? Commented Jan 15, 2020 at 21:33

1 Answer 1

0

After several tests I came to the conclusion that I should to change the code like this:

SET @code = 'a123';
SET @mid = NULL;
SELECT @mid := id, @code := code FROM my_table WHERE code = @code;
UPDATE my_table SET number = (number + 1) WHERE id = @mid;

I should use 'id' instead of 'code' after 'WHERE' in UPDATE transaction

also I should to set @code in SELECT transaction again (why? I don't know!)

This code works correctly and the previous code doesn't work correctly and I don't know the reason!

Sign up to request clarification or add additional context in comments.

Comments

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.