??? 最近看同事操作數據庫,用到了copy命令,驚嘆自己之前竟然不知道。趕緊看了一下,雖然這么命令很簡單,但是確實是很有用。
?
?
??? 首先看一下文檔里的語法定義:
COPY {FROM database | TO database | FROM database TO database}{APPEND|CREATE|INSERT|REPLACE} destination_table [(column, column, column, ...)]USING query
?
??? 下面對語法逐一說明:
?
1、DATABASE
?
??? database?對應以下的語法格式是:username[/password]@connect_identifier
?
??? 注意:如果不加密碼,則sqlplus會提示你輸入密碼。考慮到安全性,則應該不寫密碼。
?
2、FROM|TO子句
?
??? 可以注意到,在這個語法里,FROM 和 TO 兩個子句都是可以單獨出現的(當然一起出現是最常見的情況)。當沒有指定 FROM/TO 子句,則使用當前連接的數據庫。
?
??? 無論是 FROM 還是 TO 子句中連接的數據庫,都不能是 SYSDBA 或 SYSOPER 權限的用戶。
?
3、COPY類型
?
??? APPEND
??? --表存在則INSERT,不存在則CREATE
??? Inserts the rows from query into destination_table if the table exists. If destination_table does not exist, COPY creates it.
??? CREATE
??? --新建一個表,如果表存在則出錯
??? Inserts the rows from query into destination_table after first creating the table. If destination_table already exists, COPY returns an error.
???
INSERT
??? --向表中插入記錄
??? Inserts the rows from query into destination_table. If destination_table does not exist, COPY returns an error. When using INSERT, the USING query must select one column for each column in destination_table.
??? REPLACE
??? --無論表是否存在,均清空然后CREATE
??? Replaces destination_table and its contents with the rows from query. If destination_table does not exist, COPY creates it. Otherwise, COPY drops the existing table and replaces it with a table containing the copied data.
?
4、destination_table
?
??? 注意指定目標表的同時,是可以指定其字段的,但是其字段數目和類型(如果已經存在)必須與后面的query中相一致,否則報錯。
?
------------------------------------
?
??? 下面舉例說明:
?
SQL> COPY FROM HR/HR @HQ TO JOHN/kkk @WEST?REPLACE WESTEMPLOYEES?USING SELECT * FROM EMPLOYEES;
?
??? 別的沒什么可說的,但是要注意如果使用新建表的時候,新建的表的字段屬性,都是與原表相同的。在一般的情況下這都是沒有什么問題的,但是會有一種比較特殊的情況,就是例如:原始庫的字符集為ZHS16GBK,而目標庫的字符集為UTF-8,因為UTF-8中一個漢字占3個字節,而ZHS16GBK是2個。所以當原始庫中的一個屬性為varchar2(2)且為一個漢字的字段,就無法導入到UTF-8庫中了,會報錯:ORA-12899: value too large for column ...
?
??? 遇到這種情況,建議修改原始庫的字段屬性,如果沒有權限,則可以在目標庫中手工建立一下表,將字段屬性調整到合適,然后使用INSERT或者APPEND類型COPY。
?
??? 另注:select * from nls_database_parameters; 查看字符集
?
?
?
-The End-