【问题标题】:How to separate a pipe delimited column containing ranges?如何分隔包含范围的管道分隔列?
【发布时间】:2015-02-05 19:37:41
【问题描述】:

我有一个 SQL 表,其中有一列包含管道分隔的字符串,管道之间的一些元素是191087..191089 之类的范围。我需要将这些值拆分为一个列表,如果元素是一个范围,我需要列出整个范围。例如,如果元素是191087..191089,我需要列出191087,191088,191089

我能够使用以下代码将列值拆分为行范围之间作为返回数据集的一部分。

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

【问题讨论】:

标签: sql-server tsql delimiter gaps-and-islands


【解决方案1】:

对于范围,我认为您需要使用数字表或计数表。然后,您可以将第一个和最后一个值加入其中并从那里获取整个范围。

您可以在其中找到计数表的示例,该表也在 DelimitedSplit8k 中使用:

SQL, Auxiliary table of numbers

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-09-05
  • 1970-01-01
  • 2012-08-17
  • 2012-02-19
  • 2014-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多