代码之家  ›  专栏  ›  技术社区  ›  StefanE

用于替换/删除子字符串的SQL Server T-SQL语句

  •  0
  • StefanE  · 技术社区  · 14 年前

    我有一个表,其中有6列包含带有一些标记的HTML内容,现在当移动到一个新设计的站点时,大多数HTML代码都必须删除。或多或少所有标签,除了 <B> </B> .

    有没有一种很好的方法,识别所有的标签,然后删除数据中的标签?我确信测试中没有符号,所以正则表达式可能有效?

    我的另一个选择是获取每一行,处理它并更新数据库,但我猜想这可以在T-SQL中直接完成。

    我的服务器是MSSQL2008,位于托管环境中,但如果需要,我可以获取本地副本。

    谢谢, 斯特凡

    1 回复  |  直到 14 年前
        1
  •  1
  •   Martin Smith    14 年前

    使用SQL 2000中的正则表达式 http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx

    从SQL 2005到 http://weblogs.sqlteam.com/jeffs/archive/2007/04/27/SQL-2005-Regular-Expression-Replace.aspx

    修改最后一个链接会得到一个regex,它似乎在我对sql2005极其肤浅的测试中起作用。 但对于最多4000个字符的字符串 !

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using Microsoft.SqlServer.Server;
    using System.Text.RegularExpressions;
    
    public partial class UserDefinedFunctions
    {
        [Microsoft.SqlServer.Server.SqlFunction(IsDeterministic=true,IsPrecise=true)]
        public static SqlString StripAllButBoldTags(SqlString expression)
        {
            if (expression.IsNull)
                return SqlString.Null;
    
            Regex r = new Regex("</?([a-z][a-z0-9]*[^<>]*)>", RegexOptions.IgnoreCase);
    
            return new SqlString(r.Replace(expression.ToString(), new MatchEvaluator(ComputeReplacement)));
        }
    
        public static String ComputeReplacement(Match m)
        {
            return string.Compare( m.Groups[1].Value, "B",true) == 0? m.Value: "";
        }
    };