用逗号分隔截取字符串中的值

 1 declare @startpos int=1    --开始位置
 2 declare @nextpos int       --下一位置
 3 declare @spliter char=','  --分割符
 4 declare @str varchar(128)='111,222,333,444,555,666,777' --字符串
 5 declare @returnvalue varchar(3)  --截取的字符串
 6 
 7 while(@startpos<=LEN(@str))
 8  begin
 9      select @nextpos=CHARINDEX(@spliter,@str,@startpos)
10      if(@nextpos=0 or @nextpos is null)
11          begin
12              set @nextpos=LEN(@str)+1
13              set @returnvalue=RTRIM(LTRIM(SUBSTRING(@str, @startpos, @nextpos - @startpos)))
14          end
15      else  
16          begin  
17              set @returnvalue=RTRIM(LTRIM(SUBSTRING(@str, @startpos, @nextpos - @startpos)))
18          end
19          
20          SELECT @startpos = @nextpos+1
21          print(convert(varchar(10),@returnvalue))
22          --print(convert(varchar(10),@startpos))
23          --print(convert(varchar(10),@nextpos))
24  end

posted @ 2013-04-24 10:59  zhangchun  阅读(3455)  评论(0编辑  收藏  举报