The DB2 REPLACE function replaces all occurrences of a search string within a source string. If the search string is not found within the source string, the original string is returned unchanged.
The syntax for the REPLACE function is shown here:
SELECT REPLACE({source_string}, {search_string}, {replace_string}); -- After DB2 v9.7 Fix Pack 5 {replace_string} is optional SELECT REPLACE({source_string}, {search_string});
To show an example statement in use:
-- Leveraging a table column SELECT REPLACE(LONGDESCRIPTION, 'A', 'B') FROM CATENTDESC;
The above query will take the source string, defined as a field, or explicit string, in our case the LONGDESCRIPTION value from CATENTDESC and search it for the search string ‘A’. All instances of ‘A’ will then be replaced ‘B’.
NOTE: There are few things to consider regarding the REPLACE function:
- If the source, search, or replace string is not a CHAR, VARCHAR, GRAPHIC, or VARGRAPHIC data type it will be it will be cast to a VARCHAR data type before evaluation.
- Staring in DB2 Version 9.7 Fix Pack 5 and later, the replace string is optional as noted in the above examples. When the expression is an empty string or the replace string has not been specified, nothing will replace the string that is removed from the source string.
Hello,
I’m converting some VBA that uses Replace() into DB2. The VBA replace has four parameters, in my case (FieldName, StringToReplace, ReplacementString, Position), the Position being the Position in the Field Name where we want to start looking for the StringToReplace. DB2 doesn’t have a starting position, it just replaces the string anywhere in the Field. How can I specify the starting position?
Thanks!
So there isn’t a way to specify the starting position within the REPLACE function. You’ll need to work around it, but either using another function like REGEX_REPLACE (if your version of DB2 supports it), or try and work with a SUBSTR function, to find the string you need to adjust, and then replace against that SUBSTR return value.