1,4-10,30 这种形式,如何拆成 9条记录,字段值分别是1,4,5,6,7,8,9,10,30
1,4-10,30 这种形式,如何拆成 9条记录,字段值分别是1,4,5,6,7,8,9,10,30
------------------------------------
1,4-28,30
表示
1,
4,
5,
6,
7,
8,
9,
10,
30
就是要拆成9条记录,但是我如何写代码呢?
首先用逗号分割,然后横杠表示范围。
而且可能是 2,6-8,4,10-12 这种形式。
2,6-8,4,10-12
要拆分成:
2,
6,
7,
8,
4,
10,
11,
12
------解决方案--------------------
/*
功能:实现split功能的函数
*/
alter function fn_split
(
@inputstr varchar(8000),
@seprator varchar(10)
)
returns @temp table (a varchar(200))
as
begin
declare @i int
set @inputstr = rtrim(ltrim(@inputstr))
set @i = charindex(@seprator, @inputstr)
while @i > = 1
begin
insert @temp values(left(@inputstr, @i - 1))
set @inputstr = substring(@inputstr, @i + 1, len(@inputstr) - @i)
set @i = charindex(@seprator, @inputstr)
end
if @inputstr <> '\ '
insert @temp values(@inputstr)
return
end
go
create procedure test
@strIn varchar(50)
as
begin
declare test_cursor cursor scroll for
select * from dbo.fn_split(@strIn,',')
declare @c varchar(20)
declare @i int
declare @j int
open test_cursor
fetch first from test_cursor into @c
while @@FETCH_STATUS=0
begin
if (select charindex('-',@c))<1
insert into t2 values (@c)
else
begin
set @i = convert(int,left(@c,charindex('-',@c)-1))
set @j= convert(int,right(@c,len(@c)-charindex('-',@c)))
while @i<@j
begin
insert into t2 values (str(@i))
set @i=@i+1
end
end
fetch next from test_cursor into @c
end
close test_cursor
deallocate test_cursor
end
调用
exec test '1,4-10,30'