声明和使用 MySQL varchar 变量
我正在尝试使用 MySQL 5.0 中的变量进行一些简单的操作,但我无法完全让它工作。我见过许多(非常!)不同的 DECLARE/SET 语法,我不确定为什么......无论如何,我可能会混淆它们/选择错误的语法/混合它们。
这是一个失败的最小片段:
DECLARE FOO varchar(7);
DECLARE oldFOO varchar(7);
SET FOO = '138';
SET oldFOO = CONCAT('0', FOO);
update mypermits
set person = FOO
where person = oldFOO;
我也尝试用 BEGIN...END; 包装它。并作为一个程序。在这种情况下,MySQL Workbench 会很有帮助地告诉我:第一行是“')'附近的 SQL 语法错误”,第二行是“'DECLARE oldFOO varchar(7)'附近的 SQL 语法错误”。否则,它会将这两行完整地显示为错误,并在两行上显示“SQL 语法错误接近...”。
编辑:我忘了提及我已经尝试过在变量上使用和不使用@s。有些资源有它,有些则没有。
我犯了什么愚蠢的错误?
I'm trying to do some simple manipulations with variables in MySQL 5.0 but I can't quite get it to work. I've seen many (very!) different syntax for DECLARE/SET, I'm not sure why... in any case I'm presumably confusing them/picking the wrong one/mixing them.
Here's a minimal fragment that fails:
DECLARE FOO varchar(7);
DECLARE oldFOO varchar(7);
SET FOO = '138';
SET oldFOO = CONCAT('0', FOO);
update mypermits
set person = FOO
where person = oldFOO;
I've also tried wrapping it with BEGIN... END; and as a PROCEDURE. In this case MySQL Workbench helpfully tells me: "SQL syntax error near ')'" on the first line and "SQL syntax error near 'DECLARE oldFOO varchar(7)'" on the second. Otherwise it gives both lines as errors in full, with "SQL syntax error near ..." on both.
Edit: I forgot to mention that I've tried it with and without @s on the variables. Some resources had it with, others without.
What dumb mistake am I making?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这对我使用 MySQL 5.1.35 来说效果很好:
表:
This works fine for me using MySQL 5.1.35:
Table:
我使用 MySQL Workbench 遇到了同样的问题。根据 MySQL 文档,
DECLARE
“语句声明存储程序中的局部变量。”这显然意味着它只能保证与存储过程/函数一起使用。我的解决方案是简单地删除
DECLARE
语句,并在SET
语句中引入变量。对于您的代码来说,这意味着:I ran into the same problem using MySQL Workbench. According to the MySQL documentation, the
DECLARE
"statement declares local variables within stored programs." That apparently means it is only guaranteed to work with stored procedures/functions.The solution for me was to simply remove the
DECLARE
statement, and introduce the variable in theSET
statement. For your code that would mean:看来您忘记了变量声明中的@。我还记得很久以前在 MySql 中遇到
SET
问题。尝试
Looks like you forgot the @ in variable declaration. Also I remember having problems with
SET
in MySql a long time ago.Try
试试这个:
try this:
在Mysql中,我们可以使用set命令声明和使用变量,如下所示
In Mysql, We can declare and use variables with set command like below
如果您使用 phpmyadmin 添加新例程,请不要忘记将代码包装在 BEGIN 和 END 之间
If you are using phpmyadmin to add new routine then don't forget to wrap your code between BEGIN and END
例子:
Example: