SqlServer——调用C#CLR程序集方法
一、写C#方法
注意方法必须是静态的
using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace AssemblySqlFunc { public static class ConvertXMLToString { [SqlMethod] public static string ReturnValue(string xmlstr, string nodename, int x =-1) { string value = null; try { XmlDocument xx = new XmlDocument(); xx.LoadXml(xmlstr);//加载xml XmlNodeList xxList = xx.GetElementsByTagName(nodename); //取得节点名为node的XmlNode集合 if (x >= 0) { int i = 1; foreach (XmlNode xxNode in xxList) { string nodeText = xxNode.InnerText; value = nodeText; if (i == x) return value; i++; } } else { foreach (XmlNode xxNode in xxList) { string nodeText = xxNode.InnerText; value = nodeText; if (!string.IsNullOrEmpty(value)) return value; } } } catch (Exception ex) { value = "GetValue Error!"; } return value; } } }
二、在sqlserver中引入程序集
三、利用程序集创建sqlserver方法
注意: 使用程序集时不用给程序集方法传入参数,该sqlserver函数的参数会自动传入程序集方法中。
CREATE FUNCTION [dbo].[GetXMLNodeValueFunc](@xmlStr [nvarchar](max), @nodename [nvarchar](1000), @seq [int]) RETURNS [nvarchar](max) WITH EXECUTE AS CALLER AS EXTERNAL NAME [AssemblySqlFunc].[AssemblySqlFunc.ConvertXMLToString].[ReturnValue] GO
四、测试
成功拿到指定node节点的值。
五、更新CLR程序集
注意: 一定要把程序集放到权限低的文件夹下,否则会报5.拒绝访问的错误
ALTER ASSEMBLY AssemblySqlFunc FROM E:BackupAssemblySqlFunc.dll;
下一篇:
SQL语句——分组函数和分组查询