Write down SQL statements to return the result on the right side
SELECT * FROM temp;
ID | VAL |
1 | b |
2 | x,y,z |
ID | VAL |
1 | b |
2 | x |
2 | y |
2 | z |
SQL :
method 1:
create table temp_to
(
id integer
,val varchar(10)
);
insert into temp_to values (1,'b'),(2,'x,y,z');
select *
from temp_to
create table temp_num_1
(
n int
);
DECLARE @i INT;
SET @i=1
WHILE @i<=20
BEGIN
INSERT INTO temp_num_1 VALUES (@i);
SET @i=@i+1
END
select * from temp_num_1;
SELECT ID,
SUBSTRING(val,n,CHARINDEX(',',val+',',n)-n) as val
FROM temp_to
join temp_num_1
ON SUBSTRING(','+val,n,1)=','
method 2
createtable #a(id int, val varchar(2000))
insertinto #a(id, val)values (1,'a'),(2,'x,y,z'),(3,'mm,nn,pp,qq,rr,ss')
declare @delim varchar(1)=',';
with tmp(id, val, segment, lvl
)
as
(
select id,cast(val + @delim asvarchar(2000))as val,cast(''asvarchar(2000))as segment, 1 as lvl
from #a
unionall
select tmp.id,substring(tmp.val,charindex(@delim,tmp.val)+1,2000)as val,substring(tmp.val,1,charindex(@delim,tmp.val)-1)as segment, tmp.lvl +1 as lv
from tmp
where tmp.segment isnotnulland tmp.val <>''--and tmp.lvl <= 8
)
select id,segment
from tmp where lvl <> 1
本文出自 “sql_up” 博客,转载请与作者联系!