# Replacing first occurrence of certain characters in MSSQL database


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.

<figure>

![User database table](images/User-database-table-300x69.png)

<figcaption>User database table</figcaption>

</figure>

**And contains records as shown in figure below:**

<figure>

![User records before script](images/User-records-before-300x72.png)

<figcaption>User records before script</figcaption>

</figure>

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:**

```sql
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:**

<figure>

![User records after applying script](images/User-records-after-300x74.png)

<figcaption>User records after applying script</figcaption>

</figure>

 

**Reference link:** Is it possible to replace the first occurrence of a string in a column ?

## Related articles

- [Decrement a database table value if value >= 1 else... Delete the record](http://stackoverflow.com/questions/16802325/decrement-a-database-table-value-if-value-1-else-delete-the-record)
- [MS SQL Server and MSSQL$instance user account?](http://community.spiceworks.com/topic/338204-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](http://blog.sqlauthority.com/2013/05/08/sql-server-reseed-identity-in-table-column-rest-table-identity-value-sql-in-sixty-seconds-051/)

 


