替换所有出现的指定字符串值(存储在表中)?

时间:2014-09-23 20:10:58

标签: sql sql-server sql-server-2008 tsql

例如,我想在r._from中用以下脚本中的字符串t.s替换所有出现的字符串r._to

with    r(_from, _to)
          as (select    'aaa', ''
              union all
              select    'bbb', ''
              union all
              select    'ccc', ''
              -- union all ..... and more
             ),
        t(s)
          as (select    'ABCaaaDEFbbb'
              union all
              select    '123aaabbb456'
             )
    select  t.s, .... -- replace aaa, bbb, ccc, ... with empty string ''
    from    t

应该返回

ABCDEF
123456

假设有一个强大的replace函数接受替换的映射表:select replace(t.s, (select * from r)) from t,这就是问题所在。代码将放在视图中,因此我无法更新表或使用临时表。任何xquery技巧? (或者回过头来使用xquery动态创建缩进replace(replace(replace(.....的视图?)

1 个答案:

答案 0 :(得分:0)

你可以编写自己的CLR:

using System;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;

public partial class RegExBase
{
  [SqlFunction(IsDeterministic = true, IsPrecise = true)]
  public static string RegExReplace(string pattern, string matchString, string replacement)
  {
    Regex r1 = new Regex(pattern.TrimEnd(null));
    return Regex.replace(matchString.TrimEnd(null), replacement);
  }
};

然后使用它:

with r(_from, _to) as (
    select    'aaa', ''
    union all
    select    'bbb', ''
    union all
    select    'ccc', ''
-- union all ..... and more
), t(s) as (
    select    'ABCaaaDEFbbb'
    union all
    select    '123aaabbb456'
)
select dbo.RegExReplace(r.from, t.s, r.to)
  from t, r

有关详细信息,请参阅this