SQL Update Replace statement

2019-05-11 17:43发布

问题:

I need to write a sql update statement using REPLACE. The string looks like 'SE*88*000000001'. I need to replace the number between the two asterisks '*'. There is no pattern here other then that number to be replaced is always between two asterisks. Is it possible to use wild cards in this situation?

Appreciate your help.

Thanks!

回答1:

;
WITH RowSetToUpdate AS (
  SELECT
    acolumn,
    Asterisk1Pos = CHARINDEX('*', acolumn),
    Asterisk2Pos = CHARINDEX('*', acolumn, CHARINDEX('*', acolumn) + 1)
  FROM atable
  WHERE acolumn LIKE '%*%*%'
)
UPDATE RowSetToUpdate
SET acolumn = STUFF(
  acolumn,
  Asterisk1Pos + 1,
  Asterisk2Pos - Asterisk1Pos - 1,
  'replacement_string'
)

Or if it's a specific number that is to be replaced, then it would be even simpler:

UPDATE atable
SET acolumn = REPLACE(acolumn, '*88*', '*replacement_string')
WHERE acolumn LIKE '%*88*%'


回答2:

You could try using the PARSENAME function. Something like:

UPDATE YourTable
SET YourColumn =  
      PARSENAME(REPLACE(YourColumn, '*', '.'), 3)
    + '*'
    + 'whatever you want to replace the number with'
    + '*'
    + PARSENAME(REPLACE(YourColumn, '*', '.'), 1)

This would work as long as the value never contains periods and only the two *'s around the number.