Replace a character at N position in a string

坚强是说给别人听的谎言 提交于 2021-02-05 06:11:09

问题


I want to replace a character at N position in a string. This my query:

SELECT code FROM tablecodes

The result is 3 rows:

AXGETYTRTFYZUFYZFFFDIZEG
GFYZUFYZFAXFCDIZAX
ZUFYZGEFYFAXFFIXZRA

I can't figure out how to replace the last 'Z' character on each row with 'A'. I want the result to look like this:

AXGETYTRTFYZUFYZFFFDIAEG
GFYZUFYZFAXFCDIAAX
ZUFYZGEFYFAXFFIXARA

The 'Z' character is always in the same position (length of the string - 3)

Any suggestions? Thanks.


回答1:


Use Stuff Function

Example:

SELECT Stuff('AXGETYTRTFYZUFYZFFFDIZEG', Len('AXGETYTRTFYZUFYZFFFDIZEG') - 2, 1, 'A') 

Select query should be like

Select Stuff(code, Len(code) - 2, 1, 'A')



回答2:


to replace any character at particular position you can use stuff function

SELECT STUFF('XYZABC', CHARINDEX('A', 'XYZABC'), 1, '#')

as per your question here is the solution.

DECLARE @stringTable AS TABLE(STRING VARCHAR(50))
INSERT INTO @stringTable
VALUES('AXGETYTRTFYZUFYZFFFDIZEG'),
      ('GFYZUFYZFAXFCDIZAX'),
      ('ZUFYZGEFYFAXFFIXZRA')

SELECT STRING AS [Old String], 
       STUFF(STRING, LEN(STRING) - CHARINDEX('Z', REVERSE(STRING))+1, 1, 'A') AS [New String]
FROM @stringTable


 --------------------------------------------------------
|       Old String          |      New String            |
 --------------------------------------------------------
|  AXGETYTRTFYZUFYZFFFDIZEG |  AXGETYTRTFYZUFYZFFFDIAEG  |
|  GFYZUFYZFAXFCDIZAX       |  GFYZUFYZFAXFCDIAAX        |
|  ZUFYZGEFYFAXFFIXZRA      |  ZUFYZGEFYFAXFFIXARA       |
 --------------------------------------------------------



回答3:


A few ways you could do it, one way would be:

http://sqlfiddle.com/#!6/af25d/2

select left(code, len(code)-3) + 'A' + right(code, 2)
from tableCodes

note this is not doing any sort of validation that the string is long enough to perform the operations - so be careful.

Wasn't exactly sure if you would "always" have a Z as the third to last character in the string, so if you needed to check that additionally prior to making the replace you could do:

select 
    CASE WHEN SUBSTRING(code, len(code)-2, 1) = 'Z' 
        THEN left(code, len(code)-3) + 'A' + right(code, 2)
        ELSE code
    end AS code
from tableCodes


来源:https://stackoverflow.com/questions/27551749/replace-a-character-at-n-position-in-a-string

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