標籤:
在Oracle中,將一張表的資料複製到另外一個對象中。通常會有這兩種方法:insert into select 和 select into from。
前者可以將select 出來的N行(0到任意數)結果集複製一個新表中,後者只能將"一行"結果複製到一個變數中。這樣說吧,select into是PL/SQL language 的指派陳述式。而前者是標準的SQL語句。
做一個簡單測試,我們就可以很容易地看出兩者的差別。
首先,我們建立兩個表,一個作為源表,一個作為目標表。
create table t_source( id number primary key, testname varchar2(20), createtime date, flag varchar2(10) ); create table t_target( id number primary key, testname varchar2(20), createtime date, flag varchar2(10) );
接著,插入測試資料
insert into t_source values(1,‘測試資料1....1‘,sysdate-2,‘N‘); insert into t_source values(2,‘測試資料1....2‘,sysdate-2,‘N‘); insert into t_source values(3,‘測試資料1....3‘,sysdate-2,‘N‘); commit;
測試insert into select 操作
insert into test2 select * from t_source where id=1; commit;
測試select into 操作
因為select into是一個plsql語言中的複製語句,和:=實現的目標一樣。
create or replace procedure sp_sync_test is aa varchar2(100); v_record t_source%rowtype; begin select t1.testname into aa from t_source t1 where id = 1; dbms_output.put_line(‘普通變數 t1.testname= ‘ || aa); select t1.* into v_record from t_source t1 where id = 1; dbms_output.put_line(‘記錄變數 t1.testname= ‘ || v_record.testname); end;
這裡增加了原始類型的變數和記錄類型的變數,便於大家理解。
oracle中 SELECT INTO 和INSERT INTO ... SELECT區別