一个嵌套循环,然后就没有结果,也没有发现语法异常,这是如何一回事
一个嵌套循环,然后就没有结果,也没有发现语法错误,这是怎么一回事?
create function cut_func(@fet_ch varchar(30)) returns @count_table table(da_ta int)
as
begin
declare @i int,@j int,@var_c varchar(30),@temp int
set @j=1
while (@j<=len(@fet_ch))
begin
set @i=@j
set @var_c=''
while (substring(@fet_ch,@i,1)<>',')
begin
set @var_c=@var_c+substring(@fet_ch,@i,1)
set @i=@i+1
end
set @temp=cast(@var_c as int)
insert into @count_table
select @temp
set @j=@i
set @j=@j+1
end
return
end
select da_ta from cut_func('121,11')
发现一直在运行,但结果就是出不来,逻辑错误暂时也没有发现,各位大神帮我看看。
------解决思路----------------------
这个地方要这样
while (substring(@fet_ch,@i,1)<>',' AND substring(@fet_ch,@i,1)<>'')
你参考下
最后,如果是2005+建议用FOR XML PATH,如果不是用CHARINDEX好像也比较方便
------解决思路----------------------
没有处理好空字符
(substring(@fet_ch,@i,1)<>',')
可改为
SUBSTRING(@fet_ch, @i, 1) NOT IN(',','' )
提供一种 方法
create function cut_func(@fet_ch varchar(30)) returns @count_table table(da_ta int)
as
begin
declare @i int,@j int,@var_c varchar(30),@temp int
set @j=1
while (@j<=len(@fet_ch))
begin
set @i=@j
set @var_c=''
while (substring(@fet_ch,@i,1)<>',')
begin
set @var_c=@var_c+substring(@fet_ch,@i,1)
set @i=@i+1
end
set @temp=cast(@var_c as int)
insert into @count_table
select @temp
set @j=@i
set @j=@j+1
end
return
end
select da_ta from cut_func('121,11')
发现一直在运行,但结果就是出不来,逻辑错误暂时也没有发现,各位大神帮我看看。
------解决思路----------------------
这个地方要这样
while (substring(@fet_ch,@i,1)<>',' AND substring(@fet_ch,@i,1)<>'')
你参考下
create function cut_func(@fet_ch varchar(30)) returns @count_table table(da_ta int)
as
begin
declare @i int,@j int,@var_c varchar(30),@temp int
set @j=1
while (@j<=len(@fet_ch))
begin
set @i=@j
set @var_c=''
while (substring(@fet_ch,@i,1)<>',' AND substring(@fet_ch,@i,1)<>'')
begin
set @var_c=@var_c+substring(@fet_ch,@i,1)
set @i=@i+1
end
set @temp=cast(@var_c as int)
insert into @count_table
select @temp
set @j=@i
set @j=@j+1
end
return
end
最后,如果是2005+建议用FOR XML PATH,如果不是用CHARINDEX好像也比较方便
------解决思路----------------------
没有处理好空字符
(substring(@fet_ch,@i,1)<>',')
可改为
SUBSTRING(@fet_ch, @i, 1) NOT IN(',','' )
提供一种 方法
ALTER FUNCTION cut_func ( @fet_ch VARCHAR(30) )
RETURNS @count_table TABLE ( da_ta INT )
AS
BEGIN
INSERT INTO @count_table
( da_ta )
SELECT SUBSTRING(@fet_ch,number, CHARINDEX(',', @fet_ch + ',',number) - number)
FROM master.dbo.spt_values AS a
WHERE a.type = 'P'
AND CHARINDEX(',', ',' + @fet_ch, number) = number
RETURN
END
go
select da_ta from cut_func('121,11')
/*
da_ta
121
11
*/