DB2 With 拆分字串

2021-07-08 13:21:48 字數 971 閱讀 4940

假設存在表 「學生和班級的關係」,但是由於表結構的設計的問題,學生的資料的存放是將學生的id用「,」分隔連線起來存在在資料庫中的,如下圖:

班級c1中存在著10個學生,studentdids 列中存的是這10個學生的id,並以逗號分隔。

但是由於效率問題,要更改該錶,將每個學生的所在班級的資訊分開存放,class列和student列作為聯合主鍵,如下圖:

由於之前的資料已經存在,我們怎樣才能將原來的資料搬到新錶中呢?

答案如下:

insert into newclass(classid, studentid) withn(

str,

ori,

pos,

classid

) as((

select

concat(studentsids,','),

1,posstr(concat(studentsids ,','), ','),

classid

from

class

)union all

select

str,

pos+1,

locate(',', str, pos+1),

classid

from

nwhere

locate(',', str, pos+1)>0

)select

classid,

substr(str,ori,case pos-ori when -1 then 32 else pos - ori end) as result

from

n;

db2 with遞迴語句

with rpl pid,id,name as select root.pid,root.id,root.name from regr root where root.pid 8 union all select child.pid,child.id,child.name from rpl pare...

db2 with語法和遞迴

create table someplace id integer notnull primary key,parentid int,name varchar 100 insert into someplace values 001,null,陝西省 insert into someplace va...

拆分字串

拆分乙個字串,獲取每一組的key與value。如字串 qq adf f qewr98 eer d9adf t ad34 f qewrqr u adf43 gggg 2344 按照物件導向理念來解決,建立乙個物件 這個是對物件物件,有key和value兩個特性。我們需要把拆分好的資料臨時儲存起來,現在...