SQL 服务器从 Table 中替换 Select 中的删减词

SQL Server Replace Censored Words In a Select From Replace Table

我有两个表:

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 时,我想 将所有出现的子字符串 Black_Word 替换为 Replace_Word 这样我的结果看起来像:

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

我该怎么做?

这应该适合你

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

编辑:您可以使用动态替换来做到这一点。这被建议作为对不同 的回答。

-- 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')

如果您需要高性能解决方案,可以使用 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