1. 程式人生 > >SQL 語句 將一個表中用特殊字元分割的欄位轉換成多行資料

SQL 語句 將一個表中用特殊字元分割的欄位轉換成多行資料

在開始寫之前需要先說下這兩個函式的用法,

SubString(str,pos,len): 從pos位置擷取字串STR,len個字元

CHARINDEX ( expression1 ,expression2, [ start_location ] ) :expression1查詢的字元,expression2要搜尋的字元序列, 需要搜尋的其實位置

建立一個表,insert如下資料
 

create table test
( code varchar(10),
  single_No varchar(100))

 insert into  test(code,single_No)
 select '001',',201801001,201801004,201801005,201801006,'
 union 
 select '002',',201801002,201801003,201801009,201801007,201801008,'


;with temp as 
( select a.code,a.single_No, charindex(',',a.single_No) as start, charindex(',',a.single_No)-1 as lenth
  from test a
  union all
  select b.code,b.single_No,charindex(',',b.single_No,start+1), charindex(',',b.single_No,start+1)-start-1 as lenth
  from temp b 
  where start<>0
)

select  top(100) percent substring(single_No,start -lenth,lenth) as obj, code
into #te
from temp
where (start <> 0)
order by code 

轉換為多行如下圖