oracle update一个字段中的某几位
现有一张代码表,根据表中内容更新另一张表中的字段。例子:table1:old_idnew_id11111000000404440000002220200000055055...
现有一张代码表,根据表中内容更新另一张表中的字段。例子:
table1:
old_id new_id
11111000000 40444000000
22202000000 55055000000
33000000000 66000000000
table2:
id
11111302000
22202882020
33010201000
要求更新后table2:
id
40444302000
55055882020
66010201000
即:将table1中的old_id截零处理后,若table2中的id,截取相等长度后与之相等,则将table2.id的前几位变为table1.new_id
我是打算这样写的:
select rtrim(t1.new_id,'0')||substr(t2.id,length(rtrim(t1.new_id,'0'))+1,11)
from table1 t1,table2 t2
where substr(t2.id,0,length(rtrim(t1.new_id,'0'))-1)
in (select rtrim(old_id,'0') from table1)
但是这个不好使。请教大神这个具体该怎么实现,存储过程也行,但我目前自己还不会写,求借鉴。 展开
table1:
old_id new_id
11111000000 40444000000
22202000000 55055000000
33000000000 66000000000
table2:
id
11111302000
22202882020
33010201000
要求更新后table2:
id
40444302000
55055882020
66010201000
即:将table1中的old_id截零处理后,若table2中的id,截取相等长度后与之相等,则将table2.id的前几位变为table1.new_id
我是打算这样写的:
select rtrim(t1.new_id,'0')||substr(t2.id,length(rtrim(t1.new_id,'0'))+1,11)
from table1 t1,table2 t2
where substr(t2.id,0,length(rtrim(t1.new_id,'0'))-1)
in (select rtrim(old_id,'0') from table1)
但是这个不好使。请教大神这个具体该怎么实现,存储过程也行,但我目前自己还不会写,求借鉴。 展开
1个回答
展开全部
随便写了个,也可能复杂了。
创建表,插入数据:
create table table1
(old_id varchar2(20),
new_id varchar2(20));
create table table2
(id varchar2(20));
insert into table1 values ('11111000000','40444000000');
insert into table1 values ('22202000000','55055000000');
insert into table1 values ('33000000000','66000000000');
insert into table2 values ('11111302000');
insert into table2 values ('22202882020');
insert into table2 values ('33010201000');
commit;
执行:
declare
v_old_id varchar2(20);
v_new_id varchar2(20);
v_id varchar2(20);
v_str1 varchar2(20);
v_id_reverse varchar2(20);
v_s int;
cursor c_str is
select old_id, new_id from table1;
begin
open c_str;
loop
fetch c_str
into v_old_id, v_new_id;
exit when c_str%notfound;
select reverse(v_old_id) into v_id_reverse from dual;
v_s := 1;
v_id := v_new_id;
loop
select substr(v_id_reverse, v_s, 1) into v_old_id from dual;
if v_old_id = 0 then
v_s := v_s + 1;
else
select reverse(substr(v_id_reverse,
v_s,
length(v_id_reverse) - v_s + 1))
into v_str1
from dual;
exit;
end if;
end loop;
update table2 b
set b.id =
(select substr(a.new_id, 1, length(v_str1)) ||
substr(b.id,
length(v_str1) + 1,
length(b.id) - length(v_str1))
from table1 a
where substr(a.old_id, 1, length(v_str1)) =
substr(b.id, 1, length(v_str1)))
where substr(b.id, 1, length(v_str1)) = v_str1;
commit;
end loop;
close c_str;
end;
结果:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询