为数据库建立一个正则表达式函数,供查询使用
不建议使用函数,能查询到内存里面用代码解决的就用代码解决!!!
这里的方法仅供参考html
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.右键,发布
选择目标数据库便可
sql
--注意N不能遗漏 --注意sql里面的"true","false"对应1,0 where dbo.RegexMatch(table.property,N'"title":"[^"]*搜索内容[^"]*"',1)=1
1.发布报错:执行 CREATE ASSEMBLY 时失败,由于该程序集是为公共语言用户时的不受支持的版本生成的
SQL SERVER 2008R2 不支持.net4.0, 须要把项目改为.net3.5 部署成功了数据库
2.执行sql报错:禁止在 .NET Framework 中执行用户代码。启用 "clr enabled" 配置选项
执行:c#
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
参考资料:禁止在 .NET Framework 中执行用户代码。启用 "clr enabled" 配置选项函数
SQL Server 阻止了对组件 'Ole Automation Procedures' 的 过程'sys.sp_OACreate' 的访问的解决方法
SQL Server中使用正则表达式
在VS2013中新建SQL Server项目,如何使用?.net
where PATINDEX(N'%搜索内容%', table.property)>=1
这里是使用通配符匹配
PATINDEX (Transact-SQL)
返回的是匹配的位置序号,不匹配返回0,判断序号>=1,即匹配code