MySQL MySQL局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13670659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL local variables
提问by CodeKingPlusPlus
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. What/where is my error?
我在 Netbeans 中使用 MySQL,它告诉我我有一个错误。我的错误是什么/在哪里?
How can I fix this?
我怎样才能解决这个问题?
回答by eggyal
MySQL has two different types of variable:
MySQL 有两种不同类型的变量:
local variables(which are notprefixed by
@
) are strongly typed and scoped to the stored program block in which they are declared. Note that, as documented underDECLARE
Syntax:DECLARE
is permitted only inside aBEGIN ... END
compound statement and must be at its start, before any other statements.user variables(which areprefixed by
@
) are loosely typed and scoped to the session. Note that they neither need nor can be declared—just use them directly.
局部变量(不以 为前缀
@
)是强类型的,其作用域限定在声明它们的存储程序块内。请注意,如DECLARE
Syntax下所述:DECLARE
只允许在BEGIN ... END
复合语句中,并且必须在它的开头,在任何其他语句之前。用户变量(以为前缀
@
)是松散类型的并且作用域为会话。请注意,它们既不需要也不能声明——只需直接使用它们即可。
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. Otherwise, to use a "user variable", drop the DECLARE
statement.
因此,如果您正在定义一个存储程序并且实际上确实需要一个“局部变量”,根据您问题中的措辞,您将需要删除该@
字符并确保您的DECLARE
语句位于程序块的开头。否则,要使用“用户变量”,请删除该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;
回答by Rahul Tripathi
Try this:-
尝试这个:-
select @countTotal := COUNT(*) from nGrams;
回答by alditis
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 ;
回答by Olaf Dietsche
According to DECLARE Syntax, declare
must be inside a begin...end block.
根据DECLARE Syntax,declare
必须在 begin...end 块内。