2014-09-23 62 views
1

例如,我想用以下脚本中的字符串r._to替换t.s中所有出现的字符串r._from替换所有出现的指定字符串值(存储在表中)?

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技巧? (或者回落到动态创建与缩进replace(replace(replace(.....使用XQuery视图?)

+0

这可能有助于http://stackoverflow.com/questions/7844481/aggregate-replace-in-sql-server – FuzzyTree 2014-09-23 20:22:57

+0

据我所知没有b用于多次替换的内置函数,因此执行此操作的方式涉及某种类型的迭代。这可以采取循环,递归cte,游标的形式,或者使用其中一个或者甚至'select @var = ...'递归方法来滚动你自己的函数。也可以使用这些方法中的任何一种来创建和运行动态sql,它输出类似'replace(替换(替换(...')。 – 2014-09-23 20:23:35

+0

还要注意,所有常规解决方案都发生在sequence_中,如'select replace (替换('ab','a','b'),'b','a')''''aa'。 – 2014-09-23 20:29:27

回答

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

+0

交叉连接将复制't'中的行吗? – ca9163d9 2014-09-24 14:51:50

相关问题