Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Fractionner les données dans la chaîne SQL Server

Cette fonction vous aidera à séparer les chaînes :

CREATE function dbo.split(@value varchar(8000),@delim varchar(8000))
returns table
as
return
(
select d.value,
       d.orders,
       ivalue = convert(int, case when isnumeric(d.value)=1 and d.value not like '%[^0-9 +-]%' and len(replace(replace(replace(d.value,' ',''),'-',''),'+',''))<=10 then case when convert(bigint,d.value) between -2147483648 and 2147483647 then d.value end end)

    from
        (
            select   
                    value= replace(substring(value,
                                            idx,
                                            case when cnt>=0 then cnt end /* case для защиты от нехороших планов, когда сначала идет вычисление substring, а потом ограничивающее where по s_value.number between */
                                         )
                                 ,char(1),'')
                    ,orders=( datalength(left(value,idx-1))-datalength(replace(left(value,idx-1),@delim,''))
                            )/datalength(@delim)
                from (
                       select number
                             ,idx
                             ,cnt = charindex(@delim,value, number + 1) - number - datalength(@delim)
                             ,value 
                          from 
                                (
                                   select number
                                         ,idx = number + datalength(@delim)
                                         ,value = (select @delim+char(1)[email protected]+char(1)[email protected])
                                      from dbo.s_value
                                        where number between 1 and datalength( (select @delim+char(1)[email protected]+char(1)[email protected]) ) - datalength(@delim)

                                ) t            
                          where substring(t.value, number, datalength(@delim)) = @delim         
                     ) t             
       ) d          
)


GO