简体   繁体   English

从字符中多次存在的字符串中删除特定字符

[英]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; 它由姓氏,邮政编码和连字符(而不是空格)组成,然后由DATE格式的出生日期组成。

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: 只需使用CHARINDEX即可获取第一个连字符的位置,并使用STUFF替换字符:

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. 我喜欢@Salman给出的答案,但这是替代方法。 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, 您可以使用STUFF和CHARINDEX来满足您的要求,

SELECT STUFF(col, CHARINDEX('substring', col), LEN('substring'), 'replacement') FROM #temp 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. 将您的字符串替换为col,将“-”替换为子字符串,并将其替换为空白以得到正确的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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