MySQL局部变量 [英] MySQL local variables

查看:339
本文介绍了MySQL局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为查询定义和初始化MySQL变量.

I am trying to define and initialize a MySQL variable for a query.

我有以下内容:

declare @countTotal int;
SET @countTotal = select COUNT(*)
 from nGrams;

我在Netbeans中使用MySQL,它告诉我我有一个错误.我的错误在哪里?

I am using MySQL in Netbeans and it tells me I have an error. What/where is my error?

我该如何解决?

推荐答案

MySQL有两种不同类型的变量:

MySQL has two different types of variable:

  • 局部变量(不是前缀的 )是强类型的,作用域是声明它们的存储程序块.请注意,如 DECLARE语法:

  • 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 a BEGIN ... END compound statement and must be at its start, before any other statements.

  • 用户变量 (以@为前缀的 )被松散地键入并限制在会话范围内.请注意,它们既不需要也不能声明,只需直接使用它们即可.

  • 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.

    因此,如果您要定义一个存储程序并确实想要一个局部变量",则按照问题中的措辞,您需要删除@字符并确保您的DECLARE语句位于程序块的开始.否则,要使用用户变量",请删除DECLARE语句.

    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.

    此外,您可能需要将查询括在括号中才能将其作为子查询执行:

    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);
    

    否则,您可以使用 SELECT ... INTO :

    Or else, you could use SELECT ... INTO:

    SELECT COUNT(*) INTO @countTotal FROM nGrams;
    

    这篇关于MySQL局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆