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.

And contains records as shown in figure below:

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:

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
- Decrement a database table value if value >= 1 else... Delete the record
- MS SQL Server and MSSQL$instance user account?
- SQL SERVER - RESEED Identity Column in Database Table - Rest Table Identity Value - SQL in Sixty Seconds #051
