tags:

views:

1376

answers:

3

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  A: 

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.

Andrew Hare
Beat me to it. I should learn to type faster.
jschoen
Why should he even use a variable at all?
Tomalak
When I tried this, I get an error saying "Undeclared variable: id". Also when I try surrounding it with backticks `id`. Why is this?
Nik Reiman
Good point - I don't think he does for this example but he did ask how to do it.
Andrew Hare
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. :)
Nik Reiman
I think you misunderstood the SELECT INTO syntax a bit. It is for storing the results in a new table.
Tomalak
Ah yes - I am used to T-SQL :)
Andrew Hare
So am I. Actually my comment was meant to be for sqook. But since you never know with MySQL, maybe you can use the syntax to fill variables there. In T-SQL, you would do "SELECT @var = column FROM table"
Tomalak
+2  A: 

Try

INSERT INTO table2 (`number`)
SELECT id FROM table1 WHERE some_column='something' LIMIT 1
Tomalak
Ah - beat me to it - very nice!
Andrew Hare
A: 

Thanks - this saved me a ton of time!

internetoutfitters