Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SELECT... INTO with a JOIN?

I have the following example code

DECLARE 
    myRow table%rowtype 
    myVar table2.column%type
BEGIN 
    SELECT table.col1, table.col3, table.col4, table2.column
    INTO myRow 
    FROM table
    JOIN table2
    On table.col6 = table2.col1;
 END;

How can I refactor so that it is a valid statement? Can I somehow store the joined column onto myRow or myVar?

like image 990
BLaZuRE Avatar asked Aug 28 '13 19:08

BLaZuRE


People also ask

Can we use SELECT statement in join?

So, an SQL Join clause in a Select statement combines columns from one or more tables in a relational database and returns a set of data. The From is also an essential part of the Select statement and this is where it's specified which table we're pulling data from.

When we use SELECT into?

The SELECT INTO statement is a query that allows you to create a new table and populate it with the result set of a SELECT statement . To add data to an existing table, see the INSERT INTO statement instead. SELECT INTO can be used when you are combining data from several tables or views into a new table.

What does SELECT * into in SQL?

The SELECT INTO statement copies data from one table into a new table.

Does SELECT into create a table?

The SELECT INTO statement creates a new table and inserts rows from the query into it. If you want to copy the partial data from the source table, you use the WHERE clause to specify which rows to copy.


1 Answers

Your PL/SQL is valid and acceptable provided:

  1. Table TABLE contains exactly 4 columns, corresponding to the 4 values you are selecting.
  2. The query will return exactly 1 row.

If table TABLE does not contain exactly 4 columns then you need to select into something else, perhaps just 4 variables:

DECLARE 
    v_col1 table.col1%type;
    v_col3 table.col3%type;
    v_col4 table.col4%type;
    v_column table2.column%type;
BEGIN 
    SELECT table.col1, table.col3, table.col4, table2.column
    INTO v_col1, v_col3, v_col4, v_column
    FROM table
    JOIN table2
    On table.col6 = table2.col1;
END;

If your query returns more than 1 row you will get a TOO_MANY_ROWS exception; and if it returns no rows you will get a NO_DATA_FOUND exception.

like image 121
Tony Andrews Avatar answered Oct 16 '22 17:10

Tony Andrews