0

Values in the column Name_Orig look something like this: **Ang-Stl-A36-6X4X.5**Angle,A36*,4X6X1/2****

I want

  • First occurrence of ** to be replaced by Xx_
  • Second occurrence of ** to be replaced by a_
  • Replace all other * are to be with space

This is not a complete table, yet, these set of condition go in Common Table Expression(CTE)

I can replace the first occurence of ** For the second and the third point the query doesn't work

CASE 
When Name_Orig LIKE '**%' THEN 'Xx_'+ SUBSTRING(Name_Orig, 3, LEN(Name_Orig)-2)
WHEN CHARINDEX('**', Name_Orig, CHARINDEX('**', Name_Orig) + 1) > 0 THEN 
                REPLACE(STUFF(Name_Orig, CHARINDEX('**', Name_Orig, CHARINDEX('**', Name_Orig) + 1), 2, 'a_'), '*', ' ')
            ELSE Name_Orig
END

Using SQL Server 2005.

3
  • use charindex() to find first 2 occurrence and replace with the required string. for the rest, use replace()
    – Squirrel
    Commented Feb 17 at 6:22
  • 1
    FYI, 2005 ran out of support almost a decade ago. You need to get that instance upgraded, and it's going to be hard, as no shpport e versions of SQL Server support restores from 2005.
    – Thom A
    Commented Feb 17 at 9:21
  • @ITBrute how did you get on? Its customary and polite to report back when people answer your question.
    – Dale K
    Commented Feb 20 at 6:09

1 Answer 1

1

As commented by Squirrel, use patindex to find the first and second **'s and then replace to remove any remaining 8s.

select a.TestValue, replace(e.NewString,'*',' ')
from (
  values ('**Ang-Stl-A36-6X4X.5**Angle,A36*,4X6X1/2****')
) a (TestValue)
cross apply (
  values (patindex('%**%', a.TestValue))
) b (FirstPat)
cross apply (
  values (
    case
    when b.FirstPat > 0 then substring(a.TestValue, 1, b.FirstPat - 1) + 'Xx_' + substring (a.TestValue, b.FirstPat + 2, len(a.TestValue))
    else a.TestValue
    end
  )
) c (NewString)
cross apply (
  values (patindex('%**%', c.NewString))
) d (SecondPat)
cross apply (
  values (
    case
    when d.SecondPat > 0 then substring(c.NewString, 1, d.SecondPat - 1) + 'a_' + substring (c.NewString, d.SecondPat + 2, len(c.NewString)) 
    else c.NewString
    end
  )
) e (NewString);

Returns:

TestValue NewValue
Ang-Stl-A36-6X4X.5Angle,A36*,4X6X1/2**** Xx_Ang-Stl-A36-6X4X.5a_Angle,A36 ,4X6X1/2

DBFiddle

4
  • 1
    Unless I recall incorrectly, I dont think the VALUES table constructor existed in 2005.
    – Thom A
    Commented Feb 17 at 9:20
  • Arrr, oh well if OP comes back I'll re-write it
    – Dale K
    Commented Feb 17 at 9:21
  • 1
    I'll admit, my memoyof that edition is fuzzy, so it might have been 2005 added them. I think it at least had APPLY.
    – Thom A
    Commented Feb 17 at 9:23
  • Yeah I was writing simple SQL back then
    – Dale K
    Commented Feb 17 at 9:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.