0

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
gotqn
  • 42,737
  • 46
  • 157
  • 243
Siddiqui
  • 1
  • 1
  • 2
    Using DelimitedSplit8k by Jeff Moden is probably a better idea, it's a lot faster, see http://www.sqlservercentral.com/articles/Tally+Table/72993/ (code found far down) – James Z Feb 05 '15 at 19:45

1 Answers1

0

For the ranges I think you'll need to use either a numbers table or a tally table. You can then join the first and last value to that and get the whole range from there.

You can find examples for tally table in there, which is also being used in the DelimitedSplit8k:

SQL, Auxiliary table of numbers

Community
  • 1
  • 1
James Z
  • 12,209
  • 10
  • 24
  • 44
  • For a more in depth look at a tally table see Jeff's article at SSC. http://www.sqlservercentral.com/articles/T-SQL/62867/ – Sean Lange Feb 05 '15 at 19:55