使用局部变量的 SELECT INTO 问题

发布于 2024-07-12 05:30:20 字数 376 浏览 6 评论 0原文

我需要创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

坚持沉默 2024-07-19 05:30:20

您需要声明@var_name,然后选择@var_name。 我不太了解MySQL,但尝试这样的事情:

declare @var_name varchar(100);
SELECT id INTO @var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);

编辑:也许是更好的方法:

insert into table2 ('number')
select id 
from table1 
where some_column = 'something' LIMIT 1;

这不需要变量,并且将来会更快、更容易理解。

You need to declare @var_name and then select into @var_name. I don't know MySQL too well but try something like this:

declare @var_name varchar(100);
SELECT id INTO @var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);

Edit: Perhaps a better way to do it:

insert into table2 ('number')
select id 
from table1 
where some_column = 'something' LIMIT 1;

This negates the need for a variable and will be a lot faster and easier to understand down the road.

极致的悲 2024-07-19 05:30:20

尝试

INSERT INTO table2 (`number`)
SELECT id FROM table1 WHERE some_column='something' LIMIT 1

Try

INSERT INTO table2 (`number`)
SELECT id FROM table1 WHERE some_column='something' LIMIT 1
反目相谮 2024-07-19 05:30:20
CREATE TABLE table_name
AS  
SELECT ...(your select)
CREATE TABLE table_name
AS  
SELECT ...(your select)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文