Você está na página 1de 1

54 Chapter 2: Inserting

Note: A select can be more than just a SELECT. What that means is the word
select in lowercase is used in this book to refer to a query that returns a result
set. Every query or select involves at least one SELECT keyword, written in
uppercase in this book. However, a select may involve more than one SELECT, as
shown in the example above. For more information about queries, see Chapter
3, Selecting.

The result set from the SELECT in an INSERT statement is completely materi-
alized before any rows are inserted. If the target table itself is named in any
clauses of the SELECT, only those rows that already exist in the table will affect
the result set produced by the SELECT. The example below illustrates the point.
The final INSERT statement copies values from t2.non_key_1 into t1.key_1,
and the WHERE clause specifies that only values that dont already exist are to
be selected. This is an attempt to prevent any duplicate values from being
inserted into t1.key_1. It works okay for the value 1 because it already exists in
t1.key_1, but not for the value 2 because it doesnt exist in t1.key_1 before the
INSERT is started, and the statement fails with the error Primary key for table
't1' is not unique because there are two rows in t2 with the value 2.
CREATE TABLE t1 (
key_1 INTEGER NOT NULL PRIMARY KEY );

INSERT t1 VALUES ( 1 );

CREATE TABLE t2 (
key_1 VARCHAR ( 10 ) NOT NULL PRIMARY KEY,
non_key_1 INTEGER NOT NULL );

INSERT t2 VALUES ( 'A', 1 );


INSERT t2 VALUES ( 'B', 2 );
INSERT t2 VALUES ( 'C', 2 );

INSERT t1
SELECT t2.non_key_1
FROM t2
WHERE NOT EXISTS ( SELECT *
FROM t1
WHERE t1.key_1 = t2.non_key_1 );

2.2.4 INSERT Select Column List


If you want to use a select but dont want to list every single column, or you
want to rearrange the order of the columns, you can specify a column name list
in the INSERT.
<insert_select_column_list> ::= INSERT [ INTO ]
[ <owner_name> "." ] <target_table_name>
"(" <column_name_list> ")"
[ <on_existing> ]
<select_column_list>
<select_column_list> ::= <select> -- values for the specified columns
When you use this kind of INSERT, the values returned by the select are applied
to the columns in the order they are specified in the column name list. The
select must return the same number of columns, with the same or compatible
data types, in the same order as they appear in the column name list.

Você também pode gostar