I need to extract the 5 char length substring between dashes

  • example
    asdfasf-ABCDE-asdfasdfsfasf
    ss-TREWQ-asdfasfsf
    (the column is CI_NUM where that value lives)
    i need the 5 characters between the dashes
    help, (Again) . . . . 
    Much appreciated

  • jeffshelix - Tuesday, July 10, 2018 10:15 AM

    example
    asdfasf-ABCDE-asdfasdfsfasf
    ss-TREWQ-asdfasfsf
    (the column is CI_NUM where that value lives)
    i need the 5 characters between the dashes
    help, (Again) . . . . 
    Much appreciated

    If we can safely assume that there are exactly two dashes in the entire column, AND, that they are always going to contain exactly 5 characters in between them, then this should work:
    SELECT SUBSTRING(CI_NUM, CHARINDEX('-', CI_NUM) + 1, 5) AS CI_NUM_MIDDLE_PART

    Steve (aka sgmunson) 🙂 🙂 🙂
    Rent Servers for Income (picks and shovels strategy)


  • SELECT *,
         CASE WHEN start_of_value = 1 THEN ''
         ELSE SUBSTRING(CI_NUM, start_of_value, 5) END AS [5charsyouwant]
    FROM ( VALUES('asdfasf-ABCDE-asdfasdfsfasf'),('ss-TREWQ-asdfasfsf'),
         ('asdfa-12-ABCDE-kindatricky'),('nothingtoseehere'),
         ('asdf-12-ABCD-475-1-ABCDE-reallytricky')) AS data(CI_NUM)
    CROSS APPLY (
         SELECT PATINDEX('%[-][^-][^-][^-][^-][^-][-]%', CI_NUM) + 1 AS start_of_value
    ) AS alias1

    SQL DBA,SQL Server MVP(07, 08, 09) "It's a dog-eat-dog world, and I'm wearing Milk-Bone underwear." "Norm", on "Cheers". Also from "Cheers", from "Carla": "You need to know 3 things about Tortelli men: Tortelli men draw women like flies; Tortelli men treat women like flies; Tortelli men's brains are in their flies".

  • ScottPletcher - Tuesday, July 10, 2018 10:49 AM


    SELECT *,
         CASE WHEN start_of_value = 1 THEN ''
         ELSE SUBSTRING(CI_NUM, start_of_value, 5) END AS [5charsyouwant]
    FROM ( VALUES('asdfasf-ABCDE-asdfasdfsfasf'),('ss-TREWQ-asdfasfsf'),
         ('asdfa-12-ABCDE-kindatricky'),('nothingtoseehere'),
         ('asdf-12-ABCD-475-1-ABCDE-reallytricky')) AS data(CI_NUM)
    CROSS APPLY (
         SELECT PATINDEX('%[-][^-][^-][^-][^-][^-][-]%', CI_NUM) + 1 AS start_of_value
    ) AS alias1

    Sorry, not what was asked for here.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply