请问这个函数怎么写,我怎么也调不通。

jlwangzm 2003-03-20 06:14:08
比如有这样一个字符串'B0301075,WT0209006,WT0212197,WT0301008,WT0301013,WT0301043,WT0301061'
我想用逗号作分隔符,把它拆开

B0301075
WT0209006
WT0212197
WT0301008
WT0301013
……
我的想法是用substring判断逗号的绝对位置(@position1)和每次找到逗号的相对位置(@position2),再用substring将它取出来,我觉得没错,但我没调通,哪位高手帮忙看哪有问题,代码如下:
DECLARE @position1 int,@position2 int, @string char(90),@num int
SET @position1 = 1
set @num = 0
set @position2 = 1
SET @string = 'B0301075,WT0209006,WT0212197,WT0301008,WT03,,,,01013,WT0301043,WT0301061'
WHILE @position1 <= DATALENGTH(@string)

BEGIN
if CHAR(ASCII(SUBSTRING(@string, @position1, 1)))=','
set @num = @num+1
set @position2 = 1
SET @position1 = @position1 + 1
--select @position2
select char(ascII(substring(@string,@position1-@position2+1,@position2-1)))
select @position2
select @num
else
set @position2 = @position2 + 1
SET @position1 = @position1 + 1
END
其中@num是查找逗号的个数。

...全文
38 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
jlwangzm 2003-03-21
  • 打赏
  • 举报
回复
感谢pengdali和leiming两位兄弟的支持,我已经测试通过,现在买单,别嫌少,有时间我们再联系。
leimin 2003-03-20
  • 打赏
  • 举报
回复
two:
declare @str as varchar(4000)
declare @iFor int
declare @strTemp as varchar(2000)
declare @jFor int

select @str = 'B0301075,WT0209006,WT0212197,WT0301008,WT03,,,,01013,WT0301043,WT0301061'
select @iFor = 1
select @jFor = 1

while (1 = 1)
begin
select @jFor = charindex(',', @str, @jFor)
if @jFor = 0
begin
select @strTemp = right(@str, len(@str)-@iFor+1)
print @strTemp
break
end
select @strTemp = substring(@str,@iFor,@jFor-@iFor)
print @strTemp
select @iFor = @jFor+1
select @jFor = @jFor+1
end
leimin 2003-03-20
  • 打赏
  • 举报
回复
one:
declare @string varchar(1000)
declare @xh char(10)
declare @sh varchar(13)
set @string='B0301075,WT0209006,WT0212197,WT0301008,WT03,,,,01013,WT0301043,WT0301061'
set @string='select * into ##tmp from (select '''+replace(@string,',','''as str union all select ''')+''') a'
exec(@string)
--print @string
select * from ##tmp
pengdali 2003-03-20
  • 打赏
  • 举报
回复
这样就可以了!

declare @string varchar(1000)
set @string='aaaa,bbbb,cccc,dddd'
set @string='select '''+replace(@string,',','''as str union all select ''')+''''
exec(@string)

22,298

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧