我正在尝试创建一个简单的表值 CLR 函数,该函数采用逗号分隔的字符串作为参数,将其拆分并作为多行返回
根据一些在线教程,我最终得到了:
[SqlFunction(FillRowMethodName = "FillRow",TableDefinition="val nvarchar(1000)")]
public static IEnumerable SqlFunction1(SqlString val)
{
string[] splitStr = val.Value.Split(',');
return splitStr;
}
private static void FillRow(Object obj, out SqlString str)
{
object[] row = (object[])obj;
str = (string)row[0];
}
但是,使用
执行它select * from dbo.SqlFunction1('1,2,3,4,5')
返回以下错误
Msg 6260, Level 16, State 1, Line 1
An error occurred while getting new row from user defined Table Valued Function :
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Object[]'.
System.InvalidCastException:
at UserDefinedFunctions.FillRow(Object obj, SqlString& str)
.
最佳答案
我不是 C# 专家,我是 SQL 开发人员,但这段代码过去对我有用。该方法也接受参数化分隔符。 抱歉,我无法直接回答你的问题。 我什至无法向您提供来源并注明代码的原始作者 - 只能说这不是我。
using System;
using System.Data;
using System.Collections;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[SqlFunction(Name = "StringParserCLR",
FillRowMethodName = "FillRow",
TableDefinition = "string nvarchar(500)")]
public static IEnumerable StringParserCLR(SqlString str, SqlChars delimiter)
{
if (delimiter.Length == 0)
{
return new string[1] { str.Value };
}
return str.Value.Split(delimiter[0]);
}
public static void FillRow(object row, out SqlString str)
{
str = new SqlString((string)row);
}
};
关于sql-server - 创建 CLR 表值函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582449/