拆分一列为多行的问题
表数据如下
id,name,code
1,abc,c001/c002/c007
2,efg,c001/c003
3,ttt,c008/c010
怎么能转换成
id,name,code
1,abc,c001
1,abc,c002
1,abc,c007
2,efg,c001
2,efg,c003
3,ttt,c008
3,ttt,c010
SQL> create table h_t(id number ,name varchar2(20),code varchar2(50));表已创建。
SQL> begin
2 insert into h_t values (1, 'abc', 'c001/c002/c007');
3 insert into h_t values (2, 'efg', 'c001/c003');
4 insert into h_t values (3, 'ttt', 'c008/c010');
5 commit;
6 end;
7 /
PL/SQL 过程已成功完成。
SQL> select * from h_t;
ID NAME CODE---------- -------------------- --------------------------------------------------
1 abc c001/c002/c007
2 efg c001/c003
3 ttt c008/c010
SQL> create table h_t_1 as select * from h_t where rownum <1;表已创建。
SQL> declare
2 l_i number;
3 l_p number;
4 l_times number;
5 l_str varchar2(10);
6 begin
7 for x in (select * from h_t) loop
8 l_i := 1;
9 l_times := length(x.code) - length(replace(x.code, '/', '')) + 1;
10 for y in 1 .. l_times loop
11 l_p := l_i;
12 l_i := instr(x.code || '/', '/', l_i) + 1;
13 l_str := substr(x.code, l_p, l_i - l_p - 1);
14 insert into h_t_1 values (x.id, x.name, l_str);
15 end loop;
16 end loop;
17 commit;
18 end;
19 /
PL/SQL 过程已成功完成。
SQL> select * from h_t_1;
ID NAME CODE---------- -------------------- --------------------------------------------------
1 abc c001
1 abc c002
1 abc c007
2 efg c001
2 efg c003
3 ttt c008
3 ttt c010
我在把oracle数据导入sqlserver中时,发现在oracle中字段定义为唯一索引时,不同记录的此字段如果为空不被认为是重复的,但在sqlserver中如果此字段为唯一索引字段,不允许有2个以上的空值。郁闷。所以只好将sqlserver中的唯一索引字段手工修改为几个非空的值,但这样程序肯定要进行修改了。需要在程序中为此字段设置不重复 ......