I am trying to use a variable to hold the results of a stored function in MySQL. I get a syntax error that I cannot reconcile when I try to set the variable.
The name of the function is checkAddress(v1, v2, v3, v4) and returns a string. I want to put the results into a variable and then update two fields with parts of the returned string.
I am looking for the correct syntax to create and use a variable in an UPDATE statement.
UPDATE t1 n
JOIN t2 t ON n.id = t.id
SET @temp:=checkAddress(t.v1, t.v2, t.v3, t.v4),
n.address1 = LEFT(@temp, 10),
n.address2 = RIGHT(@temp, 20);
I get a syntax error at ‘@’.
I tried a test of the following:
SELECT @temp:=checkAddress(ADDRESS_1,ADDRESS_2,ADDRESS_3,ADDRESS_4) AS 'holder',
CONCAT("X",' ',@temp) FROM table;
This results in a column ‘holder’ with an ‘X’ prepended to the returned string from the function. This was to prove that variables can be set in the system and the function works.
Note: The LEFT and RIGHT functions are for illustration purposes to show that I will use the @temp variable to set other fields. It dose not matter what is after the SET @temp:= as I cannot get past this line.
2
Answers
You cannot directly set user variables within an
UPDATE
statement. However, you can achieve your goal using a subquery to assign the result of the function to a variable and then use that variable in theUPDATE
statement.For example:
The result of the
checkAddress
function for each corresponding record is stored in@temp
variable through the subquery, and then you can use@temp
in the subsequentUPDATE
statement to set the values of address1 and address2.https://sqlize.online/sql/mysql80/92ec633fe9d91409f5d890724199b9c8/
https://www.db-fiddle.com/f/x5BRNGAWzf6QXBoKvB2PEw/0