[英]MySQL local variables
I am trying to define and initialize a MySQL variable for a query. 我正在尝试为查询定义和初始化MySQL变量。
I have the following: 我有以下内容:
declare @countTotal int;
SET @countTotal = select COUNT(*)
from nGrams;
I am using MySQL in Netbeans and it tells me I have an error. 我在Netbeans中使用MySQL,它告诉我我有错误。 What/where is my error? 我的错误是什么/在哪里?
How can I fix this? 我怎样才能解决这个问题?
MySQL has two different types of variable: MySQL有两种不同类型的变量:
local variables (which are not prefixed by @
) are strongly typed and scoped to the stored program block in which they are declared. 局部变量 ( 不以@
为前缀)是强类型的,并作用于声明它们的存储程序块。 Note that, as documented under DECLARE
Syntax : 请注意,如DECLARE
语法中所述 :
DECLARE
is permitted only inside aBEGIN ... END
compound statement and must be at its start, before any other statements.DECLARE
只允许在BEGIN ... END
复合语句中使用,并且必须在其开始之前,在任何其他语句之前。
user variables (which are prefixed by @
) are loosely typed and scoped to the session. 用户变量 (以@
为前缀)被松散地键入并限定在会话中。 Note that they neither need nor can be declared—just use them directly. 请注意,它们既不需要也不能声明 - 只需直接使用它们即可。
Therefore, if you are defining a stored program and actually do want a "local variable", per the wording in your question, you will need to drop the @
character and ensure that your DECLARE
statement is at the start of your program block. 因此,如果您正在定义存储的程序并且实际上想要“局部变量”,则根据您的问题中的措辞,您将需要删除@
字符并确保您的DECLARE
语句位于程序块的开头。 Otherwise, to use a "user variable", drop the DECLARE
statement. 否则,要使用“用户变量”,请删除DECLARE
语句。
Furthermore, you will either need to surround your query in parentheses in order to execute it as a subquery: 此外,您需要在括号中包围查询,以便将其作为子查询执行:
SET @countTotal = (SELECT COUNT(*) FROM nGrams);
Or else, you could use SELECT ... INTO
: 或者,您可以使用SELECT ... INTO
:
SELECT COUNT(*) INTO @countTotal FROM nGrams;
尝试这个:-
select @countTotal := COUNT(*) from nGrams;
Function example: 功能示例:
DROP FUNCTION IF EXISTS test;
DELIMITER $$
CREATE FUNCTION test(in_number INT) RETURNS INT
BEGIN
DECLARE countTotal INT;
SET countTotal = SELECT COUNT(*) FROM nGrams;
RETURN countTotal + in_number;
END $$
DELIMITER ;
根据DECLARE语法 , declare
必须在begin ... end块内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.