0

When I run the code below inside phpmyadmin I get an error "Undefined Variable tmpportfolio"

what is the problem?

SQL:

CREATE TEMPORARY TABLE tmpportfolio (p_name VARCHAR(255),portfolio_id INT UNSIGNED NOT NULL);

SELECT p_name, portfolio_id INTO tmpportfolio
    FROM portfolio
    WHERE parent_portfolio_id IS NULL
    AND portfolio_id NOT IN
        (
           SELECT x.parent_portfolio_id
           FROM portfolio x
           WHERE x.parent_portfolio_id IS NOT NULL
        )
    AND account_id = 1

SELECT * FROM tmpportfolio;

5 Answers 5

2

SELECT field INTO variable loads the value of the field into a variable. This is why it's complaining about the variable not being defined.

What you need to do is use an INSERT INTO table (colummn) SELECT field statement instead. For instance:

INSERT INTO tmpportfolio (p_name, portfolio_id) 
SELECT p_name, portfolio_id 
FROM portfolio
WHERE parent_portfolio_id IS NULL
AND portfolio_id NOT IN
    (
       SELECT x.parent_portfolio_id
       FROM portfolio x
       WHERE x.parent_portfolio_id IS NOT NULL
    )
AND account_id = 1
Sign up to request clarification or add additional context in comments.

Comments

1

Just join first two SQL statement in one CREATE TABLE ... SELECT statment:

CREATE TABLE tmpportfolio SELECT p_name, portfolio_id FROM portfolio
    WHERE parent_portfolio_id IS NULL
    AND portfolio_id NOT IN
        (
           SELECT x.parent_portfolio_id
           FROM portfolio x
           WHERE x.parent_portfolio_id IS NOT NULL
        )
    AND account_id = 1

SELECT * FROM tmpportfolio;

Comments

1

You cannot use INTO to insert records into a table in MySql (in SQL Server, you do use INTO that way). In MySql, INTO is used to put a value into a variable.

By doing the SELECT fields INTO tmpportfolio statement, MySql thinks that tmpportfolio is now a variable and it cannot find the variable in the SELECT * ... The fix is to change the insert-records sql to something like:

INSERT INTO tmpportfolio(p_name,portfolio_id) SELECT ....;

Comments

1

The confusion seems to arise from W3Schools explaining how to do "select into table" without mentioning it's specific to some (non-Mysql) implementations. A page on dev.mysql specifically denies this possibility on Mysql, by saying:

MySQL Server doesn't support the SELECT ... INTO TABLE Sybase SQL extension. Instead, MySQL Server supports the INSERT INTO ... SELECT standard SQL syntax, which is basically the same thing.

Comments

0

I can't speak for mysql sepcifically but usually once you have created a table you insert into it it not use selct into which creates the table (and which can't since the table already exists.)

Comments

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.