Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SET user defined variable in mysql return null?

Tags:

mysql

When I created a user defined variable using

SET @a =10; 

also i checked

SET @a := 10;

the above query executed successfully. while accessing the variable it gives me NULL value instead of 10. I accessed the defined variables using this query

SELECT @a;
like image 658
Sam Arul Raj T Avatar asked Nov 05 '22 06:11

Sam Arul Raj T


1 Answers

The only way this can happen (in a client session) - and the way it happens for me from time to time - is you get bit by a short timeout on the client connection. It goes like this:

mysql> set @a = 10;

mysql> [wait for N+1 minutes, where N is the client timeout]

mysql> select @a;
+------+
| NULL |
+------+
| NULL | 
+------+
1 row in set (0.00 sec)

You have to initialize your variables and use them within a contiguous client session. When the session goes away, you lose all your variables.

The other explanation, as pointed out by others in the comments, is that the commands are hitting the server from different connections; your problem might not be a timeout, but that you are originating the "SET ..." and "SELECT ..." commands in different connections. User variables are not shared across different connections.

like image 160
D Mac Avatar answered Nov 07 '22 23:11

D Mac