注:
其他还有,CLR标量函数和聚合函数
1. C#创建dll
public class UserDefinedFunctions
{
[SqlFunction(
DataAccess = DataAccessKind.Read,
FillRowMethodName = "FillRow", //需要指定填充方法
IsDeterministic = true)]
public static IEnumerable Parse(SqlString str)
{
return new List<Item>
{
new Item
{
Key = "1",
Value = "2"
},
new Item
{
Key = "3",
Value = "4"
}
};
}
public class Item
{
public SqlString Key { get; set; }
public SqlString Value { get; set; }
}
public static void FillRow(object obj,
out SqlString key,
out SqlString value)
{
Item item = obj as Item;
key = item.Key;
value = item.Value;
}
};
2. Sql Server配置
--启用CLR
EXEC sp_configure 'clr enabled', 1
RECONFIGURE
--指定数据库
USE TestDatabase
GO
--创建assembly
CREATE ASSEMBLY [Parser] FROM 'D:\temp\ClassLibrary1.dll'
GO
--创建function
CREATE FUNCTION func_Parse(@str nvarchar(32))
RETURNS TABLE([Key] nvarchar(32),[Value] nvarchar(32))
AS EXTERNAL NAME [Parser].[UserDefinedFunctions].[Parse]
3. 调用
SELECT * FROM [dbo].[func_Parse]('123')