日期:2014-05-18  浏览次数:20449 次

要怎样的Sql语句才能完成在字符串序列取数的功能
在产品类别中要得到各类别的根类别,需要从字符串序列IDSequence
1,2
...
1,2,1
...
1,2,1,1
....
1,2,1,1,1
...

中取出第一个逗号与第二个逗号之间的数,而且还要考虑第二个逗号没有的情况。怎样写Sql,请高手指点一下,先谢了




------解决方案--------------------
declare @IDSequence nvarchar(100)
set @IDSequence= '1,2 '
select substring(@IDSequence,charindex( ', ',@IDSequence,1)+1,charindex( ', ',@IDSequence+ ', ',charindex( ', ',@IDSequence,1)+1)-charindex( ', ',@IDSequence,1)-1)

------解决方案--------------------
create table tb (col varchar(10))
insert into tb values( '1,2 ')
insert into tb values( '1,2,1 ')
insert into tb values( '1,2,1,1 ')
insert into tb values( '1,2,1,1,1 ')
go

select substring(col , charindex( ', ',col) + 1 , len(col)) col from tb
where charindex( ', ',col,charindex( ', ',col)+1) <= 0
union all
select substring(col , charindex( ', ',col) + 1 , charindex( ', ',col,charindex( ', ',col)+1) - charindex( ', ',col) - 1) col
from tb
where charindex( ', ',col,charindex( ', ',col)+1) > 0

drop table tb

/*
col
----------
2
2
2
2

(所影响的行数为 4 行)
*/