Skip to content

Replacing first occurrence of certain characters in MSSQL database

·2 min read

This post is regarding how to replace first occurrence of one or more characters from database table Column.

Suppose we have table named User with columns Id, Name, Phone Number as shown in the figure below.

User database table

User database table

And contains records as shown in figure below:

User records before script

User records before script

Now what I required to accomplish is replace the first '-' character with space ' ' so that for example phone number 214-654-1800 becomes 214 654-1800. The script for this as below and next to it is the resulting data.

MS Sql Script:

DECLARE @find varchar(8000)
SELECT @find='-' -- << Replace character
UPDATE [User]
SET [PhoneNumber]=Stuff([PhoneNumber], CharIndex(@find, [PhoneNumber]), Len(@find), ' ') -- << Replacement character

After applying the script the changes happen as in figure below:

User records after applying script

User records after applying script

 

Reference link: [Is it possible to replace the first occurrence of a string in a column ?] (Note: The original article is no longer available online)

Related articles

 

Post image