36

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.

1

7 Answers 7

75
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;
Sign up to request clarification or add additional context in comments.

6 Comments

For some reason this is returning a null, any idea why?
what is the result you get when you run SELECT salary FROM employee_info WHERE emp_id = 12345678?
I was also getting null, my error was that I had used the same variable name as my field name, so SET salary = (SELECT salary FROM.....
@Damith, There is actually 4 different syntax to accomplish this thing.
The solutions are not exactly interchangeable: SELECT INTO variable1 will not change variable1 if the result of the query is an empty set, while SET variable1 = etc. will asign NULL to variable1 in that case. I think that this difference should be pointed out, because it can be meaningful in a lot of use cases.
|
13

You can even fill multiple variables in a single query.

SELECT salary, salary_group INTO @var1, @var2 FROM employee_info WHERE emp_id = 12345678;

Comments

4

You are quite close to the right syntax. Here it is:

SET @variable1 = (SELECT salary FROM employee_info WHERE emp_id = 12345678);

and then print the variable like this:

SELECT @variable1;

Comments

2

Set the result of a query to a variable in MySQL

Select  @Amount1:=  Amount FROM table where id=57703;

1 Comment

I used eveything here but it is not working for my code
2
SELECT @code:=salary FROM employee_info WHERE emp_id = 12345678;

To check salary,

SELECT @code;

The result of salary will be initialized in code.

More Information

2 Comments

Please provide Some explantion to your query so that OP and other user may understand better
@sundarnataraj User-Defined Variables. You can find explanation @ dev.mysql.com/doc/refman/5.7/en/user-variables.html
1

use this

SELECT weight INTO @x FROM p_status where tcount=['value'] LIMIT 1;

tested and workes fine...

Comments

1
select @variable1 := salary FROM employee_info WHERE emp_id = 12345678;

3 Comments

This doesn't work dude. You need to add a colon for it to work.
change '=' to ':='
Although this code may be help to solve the problem, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.