Skip to content
Related Articles

Related Articles

Improve Article

Replace string in SQL Server

  • Last Updated : 27 Nov, 2020

Let us suppose we need to update or replace any string value in any table, we could use the below methods –

  • Replace String in SQL Server Example :
    In below example, we have a string variable, and then we are going to replace a part of a string with a new string using the Replace Function.

SQL Server Query to Replace String –

DECLARE @String_Value varchar(50)
SET @String_Value = 'This provides free and excellent knowledge on SQL Server.'
SELECT REPLACE (@String_Value, 'This', 'Geeksforgeeks');

Output :

Geeksforgeeks provides free and excellent knowledge on SQL Server.

Let us suppose we have below table named “geek_demo” :

NameSalaryCityemail
Ankit24500Delhiankit@xyz.com
Babita23600Noidababita@xyz.com
Chetan25600Noidachetan@xyz.com
Deepak24300Delhideepak@xyz.com
Isha25900Delhiisha@xyz.com
Khushi24600Noidakhushi@xyz.com
Megha25500Noidamegha@xyz.com
Parul23900Noidaparul@xyz.com




  • Replace String Example :
    In below example, we will replace a string in SQL Server SELECT Statement using the REPLACE Function while selecting data from the SQL Server table.

SQL Server Query to replace part of a string –

SELECT TOP 1000 [Name], [Salary], [City], [email], 
REPLACE([email], 'xyz.com', 'gfg.org') AS [New EmailID]
FROM [geek_demo]

Output :

NameSalaryCityemailNew EmailID
Ankit24500Delhiankit@xyz.comankit@gfg.org
Babita23600Noidababita@xyz.combabita@gfg.org
Chetan25600Noidachetan@xyz.comchetan@gfg.org
Deepak24300Delhideepak@xyz.comdeepak@gfg.org
Isha25900Delhiisha@xyz.comisha@gfg.org
Khushi24600Noidakhushi@xyz.comkhushi@gfg.org
Megha25500Noidamegha@xyz.commegha@gfg.org
Parul23900Noidaparul@xyz.comparul@gfg.org


  • Replace String in SQL Example :
    In the below example, we will replace string in SQL UPDATE Statement using the REPLACE Function in Update Statement.

SQL Server Query to replace part of a string –

UPDATE [geek_demo]
SET [email] = REPLACE([email], 'xyz.com', 'gfg.org');

Result :

(8 row(s) affected)

Now let us see the Updated table –

SELECT TOP 1000 [Name], [Salary], [City], [email]
FROM [geek_demo];

Output :

NameSalaryCityemail
Ankit24500Delhiankit@gfg.org
Babita25600Noidababita@gfg.org
Chetan25600Noidachetan@gfg.org
Deepak24300Delhideepak@gfg.org
Isha25900Delhiisha@gfg.org
Khushi24600Noidakhushi@gfg.org
Megha25500Noidamegha@gfg.org
Parul23900Noidaparul@gfg.org

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

My Personal Notes arrow_drop_up
Recommended Articles
Page :