如何将 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
How do I store a value from a SELECT statement in a variable in a MySQL Stored Procedure?
提问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 count
is 5
) into a variable? I want to be able to access the count
value throughout the rest of my procedure.
如何将这个语句的返回值(例如count
is 中的值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 @someVariable
in 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;