如何将 SELECT 语句中的值存储在 MySQL 存储过程中的变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19365758/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:07:31  来源:igfitidea点击:

How do I store a value from a SELECT statement in a variable in a MySQL Stored Procedure?

mysqlsqlstored-procedures

提问by Ethan Allen

This may be a super easy question to answer, but I am unsure how to do this correctly.

这可能是一个非常容易回答的问题,但我不确定如何正确地做到这一点。

Here is my query within the procedure:

这是我在程序中的查询:

SELECT COUNT(barcode) AS count FROM movieitems;

How do I store the return value of this statement (for example, the value in countis 5) into a variable? I want to be able to access the countvalue throughout the rest of my procedure.

如何将这个语句的返回值(例如countis 中的值5)存储到一个变量中?我希望能够在count整个过程的其余部分访问该值。

回答by

In a stored procedure do this:

在存储过程中执行以下操作:

SELECT COUNT(barcode) AS count into @myVar FROM movieitems;

回答by Hamza Kubba

SELECT @someVariable := COUNT(barcode) FROM movie ...

You can then use @someVariablein other queries. E.g.

然后您可以@someVariable在其他查询中使用。例如

SELECT * FROM some_table WHERE some_field > @someVariable;

And you can also manipulate the variable using SET:

您还可以使用SET以下方法操作变量:

SET @someVariable = @someVariable + 1;