I'm trying to code a monopoly game and I'm getting a syntax error for the following:
SET @Token = 'Thimble';
SET @Roll = 7;
UPDATE Players
SET Players.Jail = FALSE, @Roll = @Roll - 6
WHERE Players.Jail = TRUE AND Players.Token = @Token AND @Roll > 5;
Is it not possible to set the value of a temp variable as part of UPDATE? I need @roll and Players.Jail to only update if the WHERE condition is met, so I can't see a way of updating them separately.
CodePudding user response:
No, you can't SET @Roll
in an UPDATE statement. You can only SET
a column.
It's not a good practice to use tricks with temp variables like you are trying to do, because the order of evaluation of the variables is not well defined.
In this case, you should just do this:
UPDATE Players
SET Players.Jail = FALSE
WHERE Players.Jail = TRUE AND Players.Token = @Token
ORDER BY ...something...
LIMIT 1;
Using LIMIT doesn't make much sense without an ORDER BY, but I can't tell from your example which order you want to update the rows.
CodePudding user response:
With updates you can't do this directly
You could solve this with help of a further , you update the valuen to @Roll and set so the new value
CREAte tablE Players (Jail INT , token varchar(10))
INSERT INTO Players VALUES (1,'Thimble')
CREATE TABLE Rolls(Roll int); INSERT INTO Rolls VALUES(7)
SET @Token = 'Thimble'; SET @Roll = 7;
UPDATE Players,Rolls SET Players.Jail = FALSE, Rolls.Roll = @Roll - 6 WHERE Players.Jail = TRUE AND Players.Token = @Token AND @Roll > 5
SET @Roll := (SELECT Roll FROM Rolls ORDER BY 1 LIMIT 1)
SELECT @Roll
| @Roll | | ----: | | 1 |
SELECT * FROM Players
Jail | token ---: | :------ 0 | Thimble
db<>fiddle here