您的位置:首页 > 其它

循环将一张表的数据添加到另一张表,重复数据不添加

2011-11-22 13:34 281 查看
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调试
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: