This should be a simple syntax thing: I'm trying to set a variable in MySQL equal to the result of a query for instance:
SET @variable1 = SELECT salary FROM employee_info WHERE emp_id = 12345678;
Basically I want the salary from that employee to be stored as a variable that I can then manipulate and add.
What would the correct syntax for this be because I can't get it to work.
The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.
When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.
Here, we will learn about user defined variable. We can set some value to the variable with the help of SET command. SET @yourVariableName=value; Note − In the SELECT statement, the “yourVariableName” contains the NULL value and after using the SET command it contains the value which we have given.
SELECT salary INTO @variable1 FROM employee_info WHERE emp_id = 12345678 LIMIT 1;
or
SET @variable1 = (SELECT salary FROM employee_info WHERE emp_id = 12345678 LIMIT 1); SELECT @variable1;
You can even fill multiple variables in a single query.
SELECT salary, salary_group INTO @var1, @var2 FROM employee_info WHERE emp_id = 12345678;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With