迴圈將一張表的資料新增到另一張表,重複資料不新增

2021-06-02 00:38:36 字數 1875 閱讀 6383

1、迴圈將一張表的資料新增到另一張表,重複資料不新增(a表必須存在)

create or replace procedure sp_import

as i_count int;

begin

for r in (select * from a) loop

--判斷會員卡

select count(*) into i_count from b where b1= r.a1;

if i_count = 0 then

insert into b(b1,b2,b3) select a1,a2,a3 from a where a1=r.a1;

end if;

end loop;

exception

when others then

--異常處理,自己寫想要寫什麼吧

end;

--基本思路就是這樣了,自己再調調試試

或者

insert into a(a1,a2,a3) select b1,b2,b3 from b where b1 not in (select a1 from a)
2、複製表資料和結構,但是表字段的預設值設定會丟(a表必須不存在)

create table a as select * from b

3、複製表結構。

create table 表1 as select * from  表2 where 1<>1 ;

當然,關於where字句,也可以是:1=2,1=3等等

4、儲存過程異常捕捉

create or replace procedure sp_import

as i_count int;

strid varchar2(10); --新的id

i_userid int; --userid

strcomp varchar2(10); --公司id

strsql varchar2(4000);

begin

for r in (select * from a) loop

--判斷會員卡

select count(*) into i_count from b where cardid = r.擁有會員卡號;

if i_count = 0 then

strid := to_char(to_number(r.編號) + 10000);

select userid into i_userid from table where name = r.人員; --這個表你沒提供,自己對著改

select company into strcomp from tablecompany where name = r.公司; --這個表你也沒提供,自己對著改

strsql := 'insert into b(id,userid,address,company,cardid) ' ||

' values (''' || strid || ''',' || i_userid || ',''' || r.位址 ||

''',' || strcomp || ',' || r.擁有會員卡號 || ')';

execute immediate strsql;

end if;

end loop;

commit;

exception

when others then

--異常處理,自己寫想要寫什麼吧

end;

--基本思路就是這樣了,自己再調調試試

plsql 右擊儲存過程 -> 測試->彈出測試視窗->按f9除錯

mysql 將乙個表的資料新增到另一張表

下面給大家說下比較好的方法 web開發中,我們經常需要將乙個表的資料插入到另外乙個表,有時還需要指定匯入字段,設定只需要匯入目標表中不存在的記錄,雖然這些都可以在程式中拆分成簡單sql來實現,但是用乙個sql的話,會節省大量 下面我以mysql資料庫為例分情況一一說明 1.如果2張表的字段一致,並且...

Oracle查詢表結果新增到另一張表中

把每乙個知識點進行積累 oracle資料庫中將查詢一張表的結果新增到另一張表中 insert into material tc matno,mname,xlmname,lmname,tkdat,comdat,tc,id select a.matno,a.mname,a.xlnmame,a.demo2...

資料庫將一張表插入另一張表中

1.將一張表的資料插入到另一張表中 insert into seckill hjh id,code,name,drumbeating,strat time,productid,price,amount,pay time,num once,note,statu,cause,userid,check u...