CREATE FUNCTION FuncTranslate(@pTarget VarChar(50),@pSrc VarChar(50),@pDest VarChar(50))
RETURNS VarChar(50)
AS
BEGIN
DECLARE @WillOut VarChar(50) = ''
DECLARE @I int=1
DECLARE @HitPos int
if @pTarget is null RETURN(null)
while @I <= LEN(@pTarget)
BEGIN
set @HitPos = CharIndex(SubString(@pTarget,@I,1),@pSrc)
if @HitPos = 0
SET @WillOut = @WillOut + SubString(@pTarget,@I,1)
else
SET @WillOut = @WillOut + SubString(@pDest,@HitPos,1)
SET @I = @I+1
END
RETURN(@WillOut)
END;
go
with t(pTarget,pSrc,pDest) as(
select null ,'abc' ,'def' union all
select 'abc' ,'abc' ,'def' union all
select '12ab45','a1234567890','a')
select pTarget,pSrc,pDest,dbo.FuncTranslate(pTarget,pSrc,pDest) as OutVal
from t
go
pTarget pSrc pDest OutVal
------- ----------- ----- ------
NULL abc def NULL
abc abc def def
12ab45 a1234567890 a ab