Sql 替换所有出现的指定字符串值(存储在表中)?
例如,我想在下面的脚本中将t.s中出现的所有字符串r._替换为字符串r._toSql 替换所有出现的指定字符串值(存储在表中)?,sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,例如,我想在下面的脚本中将t.s中出现的所有字符串r._替换为字符串r._to with r(_from, _to) as (select 'aaa', '' union all select 'bbb', '' union all select 'ccc', '' -- union all ..... and m
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函数,它接受一个映射表进行替换:selectreplacet.s,selectfromrfromt,这就是问题所在。代码将放在视图中,因此我无法更新表或使用临时表。有xquery技巧吗?或者后退以动态创建带有缩进替换的视图。。。。。使用xquery?您可以编写自己的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
要了解更多信息,请阅读据我所知,没有用于多次替换的内置函数,因此执行此操作的方法涉及某种类型的迭代。它可以采取循环、递归cte、游标的形式,或者使用其中一个或甚至选择@var=。。。递归方法。您也可以使用这些方法中的任何一种来创建和运行动态sql,它输出类似于replace的内容……还要注意,所有正常的解决方案都是按顺序进行的,如select replace'ab',a',b',b',a'返回aa。交叉连接将复制t?