SQL Replace Statement

SQL REPLACE statement

 
The Replace statement is used to replace all occurrences of a specified string value with another string value. The Replace statement inserts or replaces values in a table. Use the Replace statement to insert new rows in a table and/or replace existing rows in a table. 
 
Replace statement will search a table for a match based on any one of the unique keys defined for that table.
 
A unique key is defined as either a Primary key constraint or a Unique constraint.
  • If this statement does not find a match, it will insert a new row into the table.
  • If this statement finds a match, it will replace that row with the column values provided.
  • If Replace statement finds a match of more than one row, it will replace the first row and it will delete all other matching rows in this table.
The Values clause must return a value for every column in the table column_name list in that same order.
 
Replace statements can be used to merge two tables based on common column values.
 
The table referenced as Replace[INTO] is the primary table and must have at least one column defined as a unique key to be used for matching. If columns referenced by the "values" clause are not of the same data type as the columns defined in the Replace table, automatic data type conversion is attempted.
 
Note 
The Replace statement performs a replacement that is not case-sensitive. 
 
The Replace statement also removes extra records that match query values, insert, update and delete privileges that are required for the target table. 
 
Syntax 
  1. REPLACE ( string_expression , string_pattern , string_replacement )   
So all occurrences of string_expression and/or string_pattern will be replaced with string_to_replacement regardless of the case of string_expression and/or string_pattern or string_replacement in the replace statement  
 
Syntax
  1. SELECT REPLACE('DEFULTSFFG','HIJ','KLM');        
  2. GO        
This example selects and replaces all the data.
 
Example
 
SQL Replace Statement
 
The following example Selects and Replaces all the data.
 
The following example uses the Collection function in Replace statement. 
 
Syntax
  1. SELECT REPLACE('This is a Sample'  COLLATE Latin1_General_BIN,        
  2. 'Sample''desk' );        
  3. GO      
Example
 
SQL Replace Statement
 
The above query will select and replace COLLATE Latin1_General BIN file to desk.
 
We can use Replace to insert or replace rows with or without the column list.
 
Syntax
  1. CREATE TABLE Students          
  2. (Id int PRIMARY KEY identity(1,1),        
  3. StudentId int)        
  4. REPLACE INTO Students (Id,StudentId) VALUES (1);         
The above query creates a table with the name "Students" and column name id as studentid, and then replaces the data in the Students table where the value is one .
 

How to replace multiple patterns in a given string statement

The following example uses the SQL replace function to replace multiple patterns of the expression 3*[4+5]/{6-8}.
 
Syntax  
  1. SELECT REPLACE(REPLACE(REPLACE(REPLACE('2*[5+5]/{7-8}''[''('), ']'')'), '{''('), '}'')');       
Example 
 
SQL Replace Statement
We can see that the Replace function is nested and it is called multiple times to replace the corresponding string as per the defined positional values within the SQL Replace function. 
 

Use Case statement

 
In this case, when you migrate a database, the dependent objects also need to be migrated; for example, a linked server or specific column values of specific tables that reference a renamed table.
 
Let’s get in-depth about the process of handling such changes dynamically using the SQL Replace function with SQL. In one complex database migration project, the server has multiple Linked Server configurations.
 
These linked servers were referred to and mentioned in multiple stored procedures. It is a matter of fact to find and replace the stored procedure scripts but the intent is to automate the entire process to make sure that we are not going to do any manual updates.
 
Let me take you through the simple steps.
 
Step 1
 
In this case, the search pattern is employee. Also, you see that the custom escape character is used to escape special characters ‘[‘and ‘]’ in the search pattern
 
Syntax
  1. DECLARE @searchPattern VARCHAR(100)= 'EmployeeDetails';      
  2. SELECT DISTINCT       
  3.        'sp_helptext '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' '      
  4. FROM syscomments      
  5. WHERE TEXT LIKE '%'+REPLACE(REPLACE(@searchPattern, ']''\]'), '[''\[')+'%' ESCAPE '\'      
  6. ORDER BY 'sp_helptext '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' ';      
Example
 
SQL Replace Statement
 
The above query declares searchPattern column name from EmployeeDetails table and select DISTINCT sp_helptext for OBJECT_SCHEMA_NAME column name In syscomments table and where TEXT contains the searchPattern column for % and '\' statement, which is further arranged according to sp_helptext and
the OBJECT_SCHEMA_NAME(id) and the OBJECT_NAME(id) function
 

How to perform a simple update to change the keyword create to the Alter table

 
This way the script is ready to execute on the target database. In some cases, you just need to retain the script. That is still fine but don’t run this step.
 
Syntax 
  1. UPDATE @sp_EmployeeDetails      
  2.   SET       
  3.      storedProcedureText = REPLACE(REPLACE(storedProcedureText, 'CREATE PROCEDURE''ALTER PROCEDURE'), @searchpattern, @replacestring);      
  4. SELECT storedProcedureText      
  5. FROM @sp_EmployeeDetails;      
  6.     
This above query updates the sp_EmployeeDetails from EmployeeDetails table Name hence setting the storeProcedureText to Replace the storeProcedureText and selecting the storedProceduretext from EmployeeDetails table. 
 

Summary

 
In this article, you learned how to use a SQL Replace statement with various options.