I have an SQL table with a column that contains a pipe delimited string and some of the elements between the pipe are ranges like 191087..191089
. I need to split these values into a list and if the element is a range, i need to list the whole range. For example, if the element is 191087..191089
, i need to list 191087,191088,191089
.
I was able to get as far as splitting the column values in to rows using the code below that i found on Code Project by 'ksababa' and modified a bit but i need help with further spliting the range and listing all the values between the rang as a part of the dataset returned.
CREATE FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
--#### Test data to play with
create table #test (
data varchar(1000),
fUND varchar(50)
)
go
insert into #test values
('Data|asdsad|sad','01')
insert into #test values
('1012|1032|1127|1134|1136|1138..1139|1141|1200..1212|1214..1223|1921|5315','09')
go
--#### Cursor to list elements values of each value of fund.
Declare c Cursor For Select Distinct fUND From #test t
Open c
DECLARE @Fund varchar(10);
create table #test1 (
Fund varchar(10),
Element varchar(10)
)
Fetch next From c into @Fund
While @@Fetch_Status=0 Begin
DECLARE @SUH VARCHAR(2000);
SET @SUH=(Select data from #test where fUND= @Fund);
insert into #test1
select @Fund , * from dbo.Split(@SUH,'|')
Fetch next From c into @Fund
End
Select * From #test1
Drop table #test1
Close c
Deallocate c