2

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.

2
  • Try running the query after explicitly clearing the value of @a. set @a= null; Commented Jul 4, 2015 at 12:55
  • 1
    @Akhil thanks, that's it. If you put it as an answer, I can give you some points... Commented Jul 4, 2015 at 12:58

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.