ITPub博客

首页 > Linux操作系统 > Linux操作系统 > update table 复杂问题二解!

update table 复杂问题二解!

原创 Linux操作系统 作者:sdusun 时间:2019-05-02 20:00:09 0 删除 编辑

表A结构如下:参考:http://www.itpub.net/showthread.php?s=&postid=5632610#post5632610

代码:

create table a
( id varchar2(4) primary key, code1 varchar2(6) not null, code2 varchar2(6) not null, code3 varchar2(4) not null, code4 varchar2(8) not null );
insert into a values (1,'0001','0012','1001','1111'); insert into a values (2,'0011','0002','1000','1002');



表B结构如下:
代码:

create table trans_code
( id varchar2(10) primary key, col_name varchar2(20) not null, --存储字段名code1,code2,code3等
fromcode varchar2
(10) not null, tocode varchar2(10) not null );
insert into trans_code values(1,'code1','0001','0011'); insert into trans_code values(2,'code2','0002','0022'); insert into trans_code values(3,'code3','1001','1011'); insert into trans_code values(4,'code4','1002','1012');

--
trans_code 表记录了需要把A表中的某个字段的from



请问,如何才能使用一条SQL语句(或者更可能高效的语句)按照trans_code表给出的转换规则将B表code进行更新?谢谢!
更新后A表结果应该是:
代码:
(1,'0011','0012','1011','1111')
(
2,'0011','0022','1000','1012')


方法一,过程嵌套游标解决

致谢:Oracle QQ群 真空




create
or replace procedure wsp_test_code
as
v_sql varchar2(1000);
v_col_name varchar2(50);
v_fromcode varchar2(30);
v_tocode varchar2(30);
cursor codecursor is select col_name,fromcode,tocode from trans_code ;
begin

open codecursor
;
loop



fetch codecursor into v_col_name
,v_fromcode,v_tocode ;

EXIT
WHEN codecursor%NOTFOUND;

v_sql := 'update a set '|| v_col_name || '='||v_tocode||' where '|| v_col_name


||'='||chr(39)||v_fromcode||chr(39);



execute immediate v_sql;

commit;


end loop;


end wsp_test_code;


方法2:没有给出update

致谢:itpub 斑竹oldwain

如果列数有限, 那么像下面这样就行了:
scott@O9I.US.ORACLE.COM> select a0.id,
2 nvl(t1.tocode, code1),
3 nvl(t2.tocode, code2),
4 nvl(t3.tocode, code3),
5 nvl(t4.tocode, code4)
6 from a0, (select * from trans_code where col_name = 'code1') t1,
7 (select * from trans_code where col_name = 'code2') t2,
8 (select * from trans_code where col_name = 'code3') t3,
9 (select * from trans_code where col_name = 'code4') t4
10 where a0.code1 = t1.fromcode (+)
11 and a0.code2 = t2.fromcode (+)
12 and a0.code3 = t3.fromcode (+)
13 and a0.code4 = t4.fromcode (+);

ID NVL(T1.TOC NVL(T2.TOC NVL(T3.TOC NVL(T4.TOC
---- ---------- ---------- ---------- ----------
1 0011 0012 1011 1111
2 0011 0022 1000 1012

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/593324/viewspace-376137/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2005-09-13

  • 博文量
    116
  • 访问量
    118268