Skip to content
Advertisement

Creating and using an SQL variable after some set text

I’m needing to set some text into a field within a row, and use a SQL variable as part of that text. I’m then using this sql statement in a bash script.

I have

select UID from table1
1

I believe I created the variable correctly

set @simpleUID := UID from table1

I then need to use this variable as follows

update table2 set exp = 'http://standurl.co/@simpleUID'

However its not working and is giving me errors about an invalid command, and some errors about improper escaping. Do I need to escape the variable when using it like this? I need that variable to be placed at the end of this URL that I’m placing into another field.

Advertisement

Answer

You’re not setting the variable correctly. It should be:

SELECT UID FROM table1 INTO @simpleUID;

or

SET @simpleUID = (SELECT UID FROM table1);

To concatenate the variable to a string, use the CONCAT() function.

update table2 set exp = CONCAT('http://standurl.co/', @simpleUID);

You can also do it in one query without the variable:

UPDATE table2 SET exp = CONCAT('http://standurl.co/', (SELECT UID FROM table1));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement