为数据库创建一个正则表达式函数,供查询使用 不建议使用函数,能查询到内存里面用代码解决的就用代码解决!!! 这里的方法仅供参考
1.新建sql server项目 2.定义正则表达式的方法
public class SqlFunction { /// 是否匹配正则表达式 /// </summary> /// <param name="input">输入的字符串</param> /// <param name="pattern">正则表达式</param> /// <param name="ignoreCase">是否忽略大小写</param> /// <returns></returns> [Microsoft.SqlServer.Server.SqlFunction] public static bool RegexMatch(string input, string pattern, bool ignoreCase) { bool isMatch = false; if (!string.IsNullOrEmpty(input) && !string.IsNullOrEmpty(pattern)) { try { Match match = null; if (ignoreCase) match = Regex.Match(input, pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled); else match = Regex.Match(input, pattern, RegexOptions.Multiline | RegexOptions.Compiled); if (match.Success) isMatch = true; } catch { } } return isMatch; } /// 获取正则表达式分组中的字符 /// </summary> /// <param name="input">输入的字符串</param> /// <param name="pattern">正则表达式</param> /// <param name="groupId">分组的位置</param> /// <param name="maxReturnLength">返回字符的最大长度</param> /// <returns></returns> [Microsoft.SqlServer.Server.SqlFunction] public static string GetRegexMatchGroups(string input, string pattern, int groupId, int maxReturnLength) { string strReturn = string.Empty; if (!string.IsNullOrEmpty(input) && !string.IsNullOrEmpty(pattern)) { try { Match match = Regex.Match(input, pattern, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled); if (match.Success && (groupId < match.Groups.Count)) { strReturn = match.Groups[groupId].Value; strReturn = (strReturn.Length <= maxReturnLength) ? strReturn : strReturn.Substring(0, maxReturnLength); } } catch { return string.Empty; } } return strReturn; } }3.配置数据库相关信息 右键-属性,设置连接字符串,可以设置多个连接 设置数据库版本 4.右键,发布 选择目标数据库即可
1.发布报错:执行 CREATE ASSEMBLY 时失败,因为该程序集是为公共语言用户时的不受支持的版本生成的 SQL SERVER 2008R2 不支持.net4.0, 需要把项目改成.net3.5 部署成功了
2.执行sql报错:禁止在 .NET Framework 中执行用户代码。启用 "clr enabled" 配置选项 执行:
exec sp_configure 'show advanced options', '1'; go reconfigure; go exec sp_configure 'clr enabled', '1' go reconfigure; exec sp_configure 'show advanced options', '1'; go参考资料:https://blog.csdn.net/heshengfen123/article/details/3597125
http://lmwlove.com/ac/ID808http://www.cnblogs.com/colder/p/3796864.htmlhttps://bbs.csdn.net/topics/390970199
这里是使用通配符匹配https://docs.microsoft.com/en-us/sql/t-sql/functions/patindex-transact-sql?view=sql-server-2017 返回的是匹配的位置序号,不匹配返回0,判断序号>=1,即匹配
转载于:https://www.cnblogs.com/Lulus/p/9497861.html
相关资源:数据库使用正则表达式