简体   繁体   中英

MySQL wrong value in variable (SELECT INTO)

I am debugging a stored procedure in MySQL and I don't know where my error is. I have following code:

SELECT refreshToken.token FROM refreshToken WHERE refreshToken.accountId = 2;

This code returns an empty set. But this code:

SELECT refreshToken.token INTO @a FROM refreshToken WHERE refreshToken.accountId = 2;
SELECT @a;

returns the first value in the table.

This is because @a is already initialized with some values.

When a query returns empty records, the global variables will retain its previous values.

So it is always a good idea to clear the variable value prior to running query

set @a = null;
SELECT refreshToken.token INTO @a FROM refreshToken WHERE refreshToken.accountId = 2;
SELECT @a;

This should show @a as null

This is to add to Akhil's answer (which is correct). Using session variables is dangerous because they can already be initialized. It is safer to initialize them whenever you use them, and one method is to do it in the query itself:

SELECT @a := refreshToken.token
FROM refreshToken CROSS JOIN
     (SELECT @a := NULL) params
WHERE refreshToken.accountId = 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM