根据sql代码中的要求输出

时间:2015-07-14 12:25:51

标签: sql

输入:' 1,2,4,5,C1,C2,C5,C7,C8,C9,T1,T5,T6,T10'

输出:1-2,4-5,C1-C2,C5,C7-C9,T1,T5-T6,T10

这里当我们给出输入之类的,逗号分隔的不同系列的字符串然后输出应该像每个带连字符的系列并用逗号分隔,只输出不应该是表格格式。

1 个答案:

答案 0 :(得分:0)

--exec SequenceSeriesReplaceByHyphen '1,2,3,11,12,13,15,16,20,21,22,C 1,C 2,C 3,C 5,C 6,C 9,72,73,T 1,T 2,T 5,T 99,55,56,57,60,61,V6,V7,V9,99,100,101' 


alter procedure dbo.SequenceSeriesReplaceByHyphen
@strInputList varchar(max)-- InputString
As

Begin

    create table dbo.#TempChar(Value Varchar(10))
    insert into #TempChar
    select Value from dbo.Split2(@strInputList) --where Value like '%[^0-9]%';

    ;With CteSplit(letter, number) 
     As(
     Select Ltrim(Rtrim(LEFT(Value, Patindex('%[0-9]%', Value) -1))),
               Cast(Right(Value, Len(Value) - Patindex('%[0-9]%', Value) + 1) AS Int)
     From #TempChar
       )
           ,Cte As (
                    Select *,RN = Number - Row_Number() Over(Partition By Letter Order BY Number)
                    From CteSplit
                    )
            ,CteFinal As(
                         Select Letter,
                                StartNumber = Min(number),
                                EndNumber = Max(number)
                         From   Cte
                         Group By letter, RN)
     Select Stuff((Select ',' + letter + '' + Cast(startNumber As varchar(Max)) +
                                              Case
                                              When startNumber = endNumber Then ''
                                              Else '-' + letter + '' + Cast(endNumber As varchar(Max))
                                              End
     From CteFinal
     Order By letter, startNumber, endNumber
     For xml Path('')),1, 1, '') as Result

End
ALTER function [dbo].[Split2](@input AS Varchar(max) )
Returns  @Result Table(Value VARCHAR(MAX))
As
Begin
      Declare @str Varchar(20)
      Declare @ind Int
      If(@input is not null)
      Begin
            Set @ind = CharIndex(',',@input)
            While @ind > 0
            Begin
                  Set @str = SUBSTRING(@input,1,@ind-1)
                  Set @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
                  Insert Into @Result values (@str)
                  Set @ind = CharIndex(',',@input)
            End
            Set @str = @input
            Insert Into @Result values (@str)
      End
      Return
End