1

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?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Why should he even use a variable at all?
When I tried this, I get an error saying "Undeclared variable: id". Also when I try surrounding it with backticks id. Why is this?
Good point - I don't think he does for this example but he did ask how to do it.
Yeah, actually, I didn't need a variable, it turns out. Sorry; I marked the other answer as correct, as it's the better solution here. :)
I think you misunderstood the SELECT INTO syntax a bit. It is for storing the results in a new table.
|
2

Try

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

1 Comment

Ah - beat me to it - very nice!
-2
CREATE TABLE table_name
AS  
SELECT ...(your select)

1 Comment

This assumes the table hasn't been created yet, which the OP didn't mention.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.