简体   繁体   English

MySQL变量值错误(SELECT INTO)

[英]MySQL wrong value in variable (SELECT INTO)

I am debugging a stored procedure in MySQL and I don't know where my error is. 我正在MySQL中调试存储过程,但我不知道我的错误在哪里。 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. 这是因为@a已经用一些值初始化了。

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 这应该显示@a为空

This is to add to Akhil's answer (which is correct). 这是为了增加Akhil的答案(正确)。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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