I read that there is a function equivalent to the standard function TRANSLATE under DB2 under SQL Server 2017. But how to do under earlier versions?
For definition of fu
Better than a WHILE loop is - at least in my eyes - the quirky update wrapped in a function:
You can maintain replace values in a table. You might add some grouping keys (e.g. for languag selection or topic focus) and pass this into the function as additional parameter:
CREATE TABLE ReplaceValues (FindChar NVARCHAR(100) NOT NULL
,ReplWith NVARCHAR(100) NOT NULL
,SortOrder INT NOT NULL);
INSERT INTO ReplaceValues VALUES('a','x',1) --all "a" will be "x"
,('test','yeah!',2) --"test" will be "yeah"
,('hello','ciao',3) --"hello" will be "ciao"
,('xxx','magic',4); --this is magic (see below)
GO
--You cannot use the quirky update inlined, but you can wrap it within a scalar function:
CREATE FUNCTION dbo.MultiReplace(@ReplaceTarget VARCHAR(MAX))
RETURNS VARCHAR(MAX)
AS
BEGIN
--Quirky Update: One of the rare situations where this is a good idea
SELECT @ReplaceTarget=REPLACE(@ReplaceTarget,rv.FindChar,rv.ReplWith)
FROM ReplaceValues AS rv
ORDER BY rv.SortOrder;
RETURN @ReplaceTarget;
END
GO
--A table with test data
declare @t table(TestString varchar(100))
insert into @t values('This string is without repls')
,('This is a test, hello, one more test')
,('See the cascade replace with aaa, which is converted to xxx, then to magic');
--...and the magic is going in here:
SELECT t.TestString
,dbo.MultiReplace(t.TestString) AS Translated
FROM @t AS t
GO
--Clean-Up
DROP FUNCTION dbo.MultiReplace;
DROP TABLE ReplaceValues;
The result
This string is without repls
This is x yeah!, ciao, one more yeah!
See the cxscxde replxce with magic, which is converted to magic, then to mxgic