SQL Update Replace statement

浪尽此生 提交于 2019-12-07 16:29:25

问题


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.



来源:https://stackoverflow.com/questions/9525184/sql-update-replace-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!