Home Forums SQL Server 2008 T-SQL (SS2K8) Need help to substring, remove string and get string RE: Need help to substring, remove string and get string

  • You data appears to have a fixed structure and the code you're looking for seems to be always between chars 4 and 9. If it's guaranteed to be like that, you can use a simple SUBSTRING. Otherwise, if the dashes delimit tokens of variable length, you can use CHARINDEX to find the first and the second dash.

    Example:

    SELECT

    acct_code_fixed = SUBSTRING(acct_code, 4, 5),

    acct_code_variable = SUBSTRING(acct_code, CHARINDEX('-',acct_code,1) + 1, CHARINDEX('-',acct_code,CHARINDEX('-',acct_code,1) - CHARINDEX('-',acct_code,1)) + 2)

    FROM table_1

    -- Gianluca Sartori