I managed to set multiple variables without using an extra temporary column by setting them within an IF()
with multiple conditions wich all have to be evaluated and use that to set a random column (for example the PK) to itself.
For example, I need to set 3 variables within the UPDATE
statement to split a string into 2 (combined with some conditions):
SET @trimmed='';
SET @firstPart='';
SET @firstSpace='';
I do that by setting id
column to itself, wrapped inside an IF()
where the variables are filled:
UPDATE `myTable`
SET
`id` = IF(
((@trimmed:=TRIM(`code_and_note`)) OR TRUE) AND
((@firstSpace:=LOCATE(' ',@trimmed)) OR TRUE) AND
(@firstPart:=IF(@firstSpace=0, '', SUBSTRING(@trimmed, 1, @firstSpace))),
`id`,
`id`
),
...
You need to OR TRUE
the assignments together else they won't be all assigned if one evaluates to FALSE.
Then you can use the variables in latter column assignments:
UPDATE `myTable`
SET
`id` = IF(...),
`code` = IF(LENGTH(@trimmed) >= 10 AND @firstSpace = 0, @trimmed, IF(LENGTH(@firstPart) >= 10, @firstPart, '')),
`note` = IF(LENGTH(@trimmed) >= 10 AND @firstSpace = 0, '', IF(LENGTH(@firstPart) >= 10, SUBSTRING(@trimmed, @firstSpace + 1), @trimmed));
See a working DB Fiddle here: https://www.db-fiddle.com/f/4UeH69PQdse1hUb9tyeGPc/0