T-SQL 中的表值函数返回列数可变的表
T-SQL 中的表值函数是否可以返回列数可变的表?
列名称可能只是1, 2, …, n
。
现在我有一个“字符串分割”函数,它返回一个单列 1 x n
表,然后我将表旋转到 nx 1
表,但我会而是通过首先返回正确的表格式来简化该过程。
我打算在 C# 中使用 CLR 过程来实现此函数,我只是不知道如何设置用户定义函数以我想要的格式返回数据:具有可变的列数,取决于输入字符串。
Is it possible to have a table-valued function in T-SQL return a table with a variable number of columns?
The column names may simply be 1, 2, …, n
.
Right now I have a "string split" function that returns a single-columned 1 x n
table, and I pivot the table afterwards to an n x 1
table, but I'd rather streamline the process by returning the correct table format to begin with.
I intend to use a CLR procedure in C# for this function, I just don't know how to set up the user-defined function to return my data in the format I want: with a variable number of columns, dependent on the input string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无论是用 T-SQL 还是 .NET / SQLCLR 编写,都不可能从表值函数 (TVF) 返回非静态结果集。只有存储过程可以动态创建结果集。
基本上,任何函数都需要返回一致的结果类型,无论是标量值还是集合(即结果集)。
但是,在 SQLCLR 存储过程中,您可以通过 SqlMetaData。只要您没有明确需要
SELECT ... FROM
,那么存储过程也许就可以工作。当然,您也可以在 T-SQL 中完成此操作,使用动态 SQL 根据 split 函数的输出构建 SELECT 语句。
这很大程度上取决于需要使用此功能的确切上下文。
It is not possible to return a non-static Result Set from a Table-Valued Function (TVF), whether it be written in T-SQL or .NET / SQLCLR. Only Stored Procedures can dynamically create a Result Set.
Basically, any function needs to return a consistent result type, whether it is a scalar value or a collection (i.e. Result Set).
However, in a SQLCLR stored procedure, you can create a dynamic Result Set via SqlMetaData. As long as you don't have an explicit need to
SELECT ... FROM
it, then maybe a stored procedure would work.Of course, you might also be able to get away with doing this in T-SQL, using dynamic SQL to construct a SELECT statement based on the output of your split function.
A lot of this comes down to the exact context in which this functionality needs to be used.