简体   繁体   中英

Remove a specific character from string where the character exists multiple times

I have a customer reference that we use internally to identify a customer when processing certain jobs. It's made up of the surname, the postcode with a hyphen instead of a space and then the date of birth in DATE format so for example;

JonesM11-1BD1978-05-05

I need to remove that hyphen from the postcode as we don't want it hyphenated going forward so the existing data that exists this way needs correcting to match.

I can't quite get my head around how to just pluck out the first of three of the same character/symbol from a string without affecting the others.

Just use CHARINDEX to get the position of first hyphen and STUFF to replace the characters:

WITH testdata(str) AS (
    SELECT 'JonesM11-1BD1978-05-05'
)
SELECT 
    str, STUFF(str, CHARINDEX('-', str), 1, '') AS str_fixed
FROM testdata

Result:

| str                    | str_fixed             |
|------------------------|-----------------------|
| JonesM11-1BD1978-05-05 | JonesM111BD1978-05-05 |

I like the answer give by @Salman, but here is an alternative. We can try just piecing together the two halves of the string about the first hyphen, which is the postal code hyphen which we want to remove.

SELECT
    str,
    LEFT(str, CHARINDEX('-', str) - 1) +
        RIGHT(str, LEN(str) - CHARINDEX('-', str)) AS str_fixed
FROM testdata;

在此处输入图片说明

Demo

You can use STUFF and CHARINDEX to achieve your requirement,

SELECT STUFF(col, CHARINDEX('substring', col), LEN('substring'), 'replacement') FROM #temp

place your string in place of col, '-' in substring, and blank in replacement to get right answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM