Sei sulla pagina 1di 1

Chapter 2: Inserting 55

Data may be copied between tables even if they have different schema.
Here is an example where t1.key_1 is converted to VARCHAR and placed in
t2.col_3, t1.non_key_1 is copied into t2.col_2, and all the other columns of t2
are assigned their default values:
CREATE TABLE t1 (
key_1 INTEGER NOT NULL,
non_key_1 VARCHAR ( 100 ) NOT NULL,
PRIMARY KEY ( key_1 ) );

CREATE TABLE t2 (
key_col INTEGER NOT NULL DEFAULT AUTOINCREMENT,
col_2 VARCHAR ( 100 ) NOT NULL,
col_3 VARCHAR ( 100 ) NOT NULL,
updated_by VARCHAR ( 128 ) NOT NULL DEFAULT LAST USER,
last_updated TIMESTAMP NOT NULL DEFAULT TIMESTAMP,
PRIMARY KEY ( key_col ) );

INSERT t2 ( col_3, col_2 )


SELECT key_1, non_key_1
FROM t1;

Tip: Watch out for problems caused by implicit data conversions when values
are inserted into columns with different data types. Long strings may be silently
truncated when inserted into columns with short maximum lengths. Also, there
are problems with precision when converting between NUMERIC and FLOAT
data types, and with data types when expressions involving values of different
types are computed and the results inserted. For example, the expression 1 +
32767 will be stored as 32768 when inserted into a SMALLINT column.

2.2.5 INSERT Select With Auto Name


The WITH AUTO NAME clause lets you omit the column name list from the
INSERT while still using a select that omits some columns or specifies columns
in a different order. Columns in the target table are automatically matched up,
by name, with the values returned by the select. This means each value returned
by the select must have a name, either a column name or an alias name, and that
name must match a column name in the target table.
<insert_select_auto_name> ::= INSERT [ INTO ]
[ <owner_name> "." ] <target_table_name>
[ <on_existing> ]
WITH AUTO NAME
<select_auto_name>
<select_auto_name> ::= <select> -- with names or aliases to match target columns
The following example shows how values are specified for col_2, col_3, and
col_4 in t2 by using alias names in the SELECT:
CREATE TABLE t1 (
key_1 INTEGER NOT NULL,
non_key_1 VARCHAR ( 100 ) NOT NULL,
PRIMARY KEY ( key_1 ) );

CREATE TABLE t2 (
key_col INTEGER NOT NULL DEFAULT AUTOINCREMENT,
col_2 VARCHAR ( 100 ) NOT NULL,
col_3 VARCHAR ( 100 ) NOT NULL,
col_4 VARCHAR ( 100 ) NOT NULL,

Potrebbero piacerti anche