Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the result of a query to a variable in MySQL

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.

like image 331
NateSHolland Avatar asked May 24 '12 16:05

NateSHolland


People also ask

How do you assign results of a query to a variable in MySQL?

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.

How do you assign a query to a variable in SQL?

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.

How do you declare and assign a value to a variable in MySQL?

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.


2 Answers

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; 
like image 178
Damith Avatar answered Sep 17 '22 20:09

Damith


You can even fill multiple variables in a single query.

SELECT salary, salary_group INTO @var1, @var2 FROM employee_info WHERE emp_id = 12345678; 
like image 28
Olias Avatar answered Sep 17 '22 20:09

Olias