sql-server - 创建 CLR 表值函数

标签 sql-server clr

我正在尝试创建一个简单的表值 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/

相关文章:

sql-server - 将 SQL Server Management Studio Express 导出到 GoDaddy 时出现问题

sql-server - Visual Studio 2010 中的数据库设计器

sql - 从 SQL 表中查找不连续性

clr - asp.net mvc 6如何知道 Controller 不继承自Controller类时要添加哪些资源?

visual-studio-2010 - No_CLR_Support 具有 C++/CLI 源文件的 C++ 项目

sql-server - 人员可用性的数据库设计

mysql - MySql 中的@@DBTS

c# - 为什么在尝试 Assembly.ReflectionOnlyLoad 时没有执行 ReflectionOnlyAssemblyResolve?

c# - 装箱和拆箱

c# - 为什么 CLR ThreadPool 工作线程使用 LIFO 顺序处理来自本地队列的任务?