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

  • I might play with some possibilities, but here's an option that doesn't need concatenation.

    IF OBJECT_ID('dbo.SubstringIndex') IS NOT NULL

    DROP FUNCTION dbo.SubstringIndex

    GO

    CREATE FUNCTION dbo.SubstringIndex(

    @SourceString varchar(8000),

    @delim char(1),

    @idx int

    )

    RETURNS TABLE WITH SCHEMABINDING

    RETURN

    WITH

    E(n) AS(

    SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)

    ),

    E2(n) AS(

    SELECT a.n FROM E a, E b

    ),

    E4(n) AS(

    SELECT a.n FROM E2 a, E2 b

    ),

    cteTally(n) AS(

    SELECT TOP(LEN(@SourceString)) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n

    FROM E4

    ),

    ctePosition(n) AS(

    SELECT TOP( @idx) n

    FROM cteTally

    WHERE SUBSTRING(@SourceString, n, 1) = @delim

    )

    SELECT LEFT( @SourceString, MAX(n) - 1) String

    FROM ctePosition;

    go

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

    @delim char(1) = '.',

    @idx int = 2;

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

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2