使用局部变量的 SELECT INTO 问题
我需要创建一个 SQL 查询,根据 SELECT 查询的结果将一些数据插入到表中的局部变量中。 我的数据库平台是 MySQL 5.1,但我认为这不会有什么不同。 基本上,我想做的是:
SELECT id INTO var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);
但是,我无法通过第一个语句,因为我收到错误“未声明的变量 var_name”。 我还尝试将语句放入 BEGIN/END 块和存储过程中,但随后遇到其他错误,这些错误仅说明 SELECT 行上存在错误。 我究竟做错了什么?
I need to create an SQL query to insert some data into a table based on the results of a SELECT query into a local variable. My DB platform is MySQL 5.1, but I don't think that should make a difference here. Basically, what I want to do is:
SELECT id INTO var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);
I can't get past the first statement, though, as I get the error "Undeclared variable var_name". I've also tried putting the statement in a BEGIN/END block, and a stored procedure, but then I encounter other errors which state only that there is an error on the SELECT line. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要声明
@var_name
,然后选择@var_name
。 我不太了解MySQL,但尝试这样的事情:编辑:也许是更好的方法:
这不需要变量,并且将来会更快、更容易理解。
You need to declare
@var_name
and then select into@var_name
. I don't know MySQL too well but try something like this:Edit: Perhaps a better way to do it:
This negates the need for a variable and will be a lot faster and easier to understand down the road.
尝试
Try