Home Forums SQL Server 2008 T-SQL (SS2K8) SQL Server equivalent for MySQL's Substring_index RE: SQL Server equivalent for MySQL's Substring_index

  • Excellent solution Lynn! I made some modifications to also specify a starting position. I am using this to parse a comma-delimited flat file error output from an SSIS package. Modifications are in bold:

    set ansi_padding on;

    go

    create function dbo.SubstringIndex(

    @SourceString varchar(8000),

    @delim char(1),

    @idx int,

    @start int

    )

    returns table with schemabinding

    return

    with stritems as (

    select

    ItemNumber,

    Item

    from

    dbo.DelimitedSplit8k(@SourceString,@delim)

    )

    select

    Item = stuff((select @delim + si.Item

    from stritems si

    where si.ItemNumber > @start and si.ItemNumber <=@idx

    order by si.ItemNumber

    for xml path(''),TYPE).value('.','varchar(8000)'),1,1,'')

    go

    declare @SourceStr varchar(8000) = 'www.mytestpage.info',

    @delim char(1) = '.',

    @idx int = 2,

    @start int=0;

    select * from dbo.SubstringIndex(@SourceStr,@delim,@idx,@start);

    go