是否可以在SQL CLR用户定义类型中创建表值*方法*?

Pet*_*hia 12 sql-server sqlclr user-defined-types sql-server-2008

我有一个CLR UDT,它将从表值方法中受益匪浅,ala xml.nodes():

-- nodes() example, for reference:
declare @xml xml = '<id>1</id><id>2</id><id>5</id><id>10</id>'
select c.value('.','int') as id from @xml.nodes('/id') t (c)
Run Code Online (Sandbox Code Playgroud)

我想要一些类似我的UDT:

-- would return tuples (1, 4), (1, 5), (1, 6)....(1, 20)
declare @udt dbo.FancyType = '1.4:20'
select * from @udt.AsTable() t (c)
Run Code Online (Sandbox Code Playgroud)

有没有人有这方面的经验?任何帮助将不胜感激.我尝试了一些事情,但都失败了.我找了文档和示例,但没有找到.

是的,我知道我可以创建以UDT为参数的表值UDF,但我非常希望将所有内容捆绑在单一类型中,OO风格.

编辑

Russell Hart发现文档声明不支持表值方法,并修复了我的语法以产生预期的运行时错误(见下文).

在VS2010中,在创建新的UDT之后,我在结构定义的末尾添加了这个:

[SqlMethod(FillRowMethodName = "GetTable_FillRow", TableDefinition = "Id INT")]
public IEnumerable GetTable()
{
    ArrayList resultCollection = new ArrayList();
    resultCollection.Add(1);
    resultCollection.Add(2);
    resultCollection.Add(3);
    return resultCollection;
}

public static void GetTable_FillRow(object tableResultObj, out SqlInt32 Id)
{
    Id = (int)tableResultObj;
}
Run Code Online (Sandbox Code Playgroud)

这成功构建和部署.但是在SSMS中,我们得到了预期的运行时错误(如果不是逐字逐句):

-- needed to alias the column in the SELECT clause, rather than after the table alias.
declare @this dbo.tvm_example = ''
select t.[Id] as [ID] from @this.GetTable() as [t]

Msg 2715, Level 16, State 3, Line 2
Column, parameter, or variable #1: Cannot find data type dbo.tvm_example.
Parameter or variable '@this' has an invalid data type.
Run Code Online (Sandbox Code Playgroud)

所以,似乎毕竟不可能.考虑到在SQL Server中改变CLR对象的限制,即使可能,也可能不是明智之举.

也就是说,如果有人知道解决这个特殊限制的黑客行为,我会相应地提出新的赏金.

小智 8

您已将表别名但不是列.尝试,

declare @this dbo.tvm_example = ''
select t.[Id] as [ID] from @this.GetTable() as [t]
Run Code Online (Sandbox Code Playgroud)

根据文档http://msdn.microsoft.com/en-us/library/ms131069(v=SQL.100).aspx#Y4739,这应该在关于不正确类型的另一个运行时错误上失败.

SqlMethodAttribute类继承自SqlFunctionAttribute类,因此SqlMethodAttribute继承SqlFunctionAttribute中的FillRowMethodName和TableDefinition字段.这意味着可以编写表值方法,但实际情况并非如此.该方法编译和程序集部署,但在运行时引发有关IEnumerable返回类型的错误,并显示以下消息:"程序集中的"方法,属性或字段''''具有无效的返回类型."

他们可能正在避免支持这种方法.如果使用方法更新更改程序集,则可能会导致UDT列中的数据出现问题.一个合适的解决方案是拥有一个最小的UDT,然后是一个单独的方法来伴随它.这将确保灵活性和功能齐全的方法.

xml nodes方法不会更改,因此它不受相同的实现限制.

希望这有助于彼得并祝你好运.