Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Update Replace statement

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!

like image 819
OBL Avatar asked Jun 14 '26 15:06

OBL


1 Answers

;
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*%'
like image 138
Andriy M Avatar answered Jun 16 '26 08:06

Andriy M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!