SQL Server替换从替换表中选择的删失字

时间:2016-02-16 21:35:18

标签: sql sql-server ssms

我有两张桌子:

Word_Blacklist

  | Black_Word | Replace_Word
1 | foo        | f**
2 | bar        | b**

ESCodes

  | Beircht
1 | this bar has good food
2 | foo foo sentences

从ESCodes选择Bericht时我想 Replace_Word 替换所有出现的子串 Black_Word ,这样我的结果如下所示:

this b** has good f**d
f** f** sentences

我该怎么做?

3 个答案:

答案 0 :(得分:1)

这应该对你有用

select IIF(exists(select name from table2), '****', name)
from table1

答案 1 :(得分:1)

编辑:您可以使用动态替换执行此操作。建议将其作为不同question的答案。

-- first generate the replace statement with all Black_Words
declare @replace varchar(max)
select @replace = coalesce ('replace(' + @replace,'replace(bericht') + ',''' + Black_Word + ''',''' + Replace_Word + ''')'
FROM Word_Blacklist

-- execute statement
exec( 'select ' + @replace + 'from ESCodes')

答案 2 :(得分:0)

如果您需要高性能解决方案,可以使用Eval SQL.NET轻松完成

免责声明:我是该项目的所有者Eval SQL.NET

该库允许您直接在SQL中使用C#语法。

DECLARE @tableMessage TABLE ( Msg VARCHAR(250) )

DECLARE @tableReplace TABLE
    (
      Original_Word VARCHAR(50) ,
      Replace_Word VARCHAR(50)
    )

INSERT  INTO @tableMessage
        ( Msg )
VALUES  ( 'A test to replace FromWord1 and FromWord2!' ),
        ( 'FromWord1FromWord1FromWord1 FromWord1 FromWord2' )


INSERT  INTO @tableReplace
        ( Original_Word, Replace_Word )
VALUES  ( 'FromWord1', 'ToWord1' ),
        ( 'FromWord2', 'ToWord2' )


DECLARE @sqlnet SQLNET = SQLNET::New('')
DECLARE @sql VARCHAR(MAX) = 'template'
DECLARE @pos VARCHAR(10) = '0';

-- CREATE the sql and set parameter value
SELECT  @sql = @sql + '.Replace(old_' + @pos + ', new_' + @pos + ')' ,
        @sqlnet = @sqlnet.ValueString('old_' + @pos, Original_Word)
                         .ValueString('new_' + @pos, Replace_Word) ,
        @pos = CAST(@pos AS INT) + 1
FROM    @tableReplace

-- SET the code to evaluate
-- template.Replace(old_0, new_0).Replace(old_1, new_1)
SET @sqlnet = @sqlnet.Code(@sql).Root();

-- Evaluate the code
SELECT  Msg ,
        @sqlnet.ValueString('template', Msg).EvalString()
FROM    @tableMessage AS A