简体   繁体   中英

Replace ONLY the first occurrence of a string in SQL

I have to update all phone numbers that start with 00 by replacing the 00 with a '+' prefix. I must replace only the first occurrence of 00 and nothing else.

phone_number:     000258843300081
ActualResult:     +02588433+081
ExpectedResult:   +0258843300081

Incorrect Query Used:

    UPDATE [dbo].[phone]
    SET phone_number = REPLACE(phone_number, '00', '+')
    WHERE phone_number_numeric LIKE '00%'

Just use STUFF() :

UPDATE [dbo].[phone]
    SET phone_number = STUFF(phone_number, 1, 2, '+')
    WHERE phone_number_numeric LIKE '00%';

Here's the correct query. Just convert to an update command! Also, I've used a generic approach to solve the problem.

    SELECT 
      phone_number
    , STUFF(phone_number, CHARINDEX('00', phone_number), LEN('00'), '+') as ExpectedResult
    FROM dbo.phone 
    WHERE phone_number_numeric LIKE '00%'

The REPLACE function looks at the entire string. Use STUFF function to narrow the scope down to the desired limit.

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