遇到一個狀況,資料庫顯示為
| CODE | FK |
-----------------------
| A | 1,2,3 |
我需要轉如下才能關聯....
| CODE | FK |
-----------------------
| A | 1 |
| A | 2 |
| A | 3 |
解法 :
參考 :
https://stackoverflow.com/questions/13527537/sql-query-to-split-column-data-into-rows
先建立sql function
create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))
returns @temptable TABLE (items varchar(MAX))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end;
然後下以下sql 句即可
select t1.Code, s.items FK
from [table] t1
outer apply dbo.Split(t1.FK, ',') s
outer apply : 說明參考
https://ithelp.ithome.com.tw/articles/10195219