Home Forums SQL Server 2008 T-SQL (SS2K8) how to use substring and charindex to extract desired string RE: how to use substring and charindex to extract desired string

  • SELECT

    MyString,

    x.p1, y.p2, z.p3,

    LeftBitty = LEFT(MyString,NULLIF(z.p3,0)-1)

    FROM (VALUES ('ek/df/cv/'), ('ek/df/cv/f'), ('ek/df/cvf')) d (MyString)

    CROSS APPLY (SELECT p1 = CHARINDEX('/',MyString,0)) x

    CROSS APPLY (SELECT p2 = CHARINDEX('/',MyString,p1+1)) y

    CROSS APPLY (SELECT p3 = CHARINDEX('/',MyString,p2+1)) z

    SELECT

    MyString,

    z.p3,

    LeftBitty = LEFT(MyString,NULLIF(z.p3,0)-1)

    FROM (VALUES ('ek/df/cv/'), ('ek/df/cv/f'), ('ek/df/cvf')) d (MyString)

    CROSS APPLY (SELECT p3 = CHARINDEX('/',MyString,CHARINDEX('/',MyString,CHARINDEX('/',MyString,0)+1)+1)) z

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden