【发布时间】:2013-04-30 10:20:24
【问题描述】:
我想知道,是否有任何方法可以将列名添加到 Sql Server 中的 CLR 标量函数。我的意思是,在我运行查询后,我希望看到一个列,其中该函数的结果已经用自定义而不是 (No column name) 命名。
我知道函数经常组合在一起,或者出于其他原因我不得不将它们命名为不同的名称,但仍然 - 当您编写一个包含 30 列的查询时,不必为其中的 20 列输入别名会做个好人。
那么有谁知道可以实现这一点的 hack 吗?
通过 SSMS 中的一些插件拥有此功能也很不错(例如,从计算中使用的函数和列构建虚拟别名,例如“datediff_startdate_enddate”)。我试图找到一个现成的解决方案,但没有效果。有什么提示吗?
编辑: 有人问我有关代码示例的问题。我认为这不会有太大帮助,但它是:
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using System.Text.RegularExpressions;
namespace ClrFunctions
{
public class RegexFunctions
{
public static SqlBoolean clrIsMatch(SqlString strInput, SqlString strPattern)
{
if (strPattern.IsNull || strInput.IsNull)
{
return SqlBoolean.False;
}
return (SqlBoolean)Regex.IsMatch(strInput.Value, strPattern.Value, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
}
T-SQL:
Create Assembly ClrFunctions From 'C:\CLR\ClrFunctions.dll'
GO
Create Function dbo.clrIsMatch(
@strInput As nvarchar(4000),
@strPattern As nvarchar(255)
)
Returns Bit
As External Name [ClrFunctions].[ClrFunctions.RegexFunctions].[clrIsMatch]
GO
这是我希望在 T-SQL 中对该函数的调用和预期结果:
select
txt, dbo.clrIsMatch(txt,'[0-9]+')
from (
select 'some 123 text' as txt union all
select 'no numbers here' union all
select 'numbers 456 again'
) x
Result 已有列名,无需在 T-SQL 中添加别名:
【问题讨论】:
-
也许一个具体的例子会有助于得到一些回应:你能展示一个最小的代码示例吗? MSDN 中的 examples 表明 CLR 函数确实(或可以)在其结果集中提供列名。
-
您可以为表值函数添加列名,但这不是我的意思。我想为标量函数提供列名。不过谢谢你的评论。
-
好的,因为您从未使用过不明显的“标量”一词,尽管据我所知,标量函数在 SQL Server 中从来没有列别名。毕竟,他们不返回列。但我已经编辑了你的问题标题和标签,希望能让问题更清晰,得到更好的回答。
-
好的,我应该指出我的意思是标量函数。但是在您编辑之后,现在看起来我不知道如何为 T-SQL 中的列添加别名:)。 C# 在这里至关重要,> 可能
-
SELECT dbo.f()不返回带有(No column name)的值,无论它是 TSQL 还是 CLR 函数?这就是为什么我建议发布一些示例代码以尽可能清楚地说明您如何调用函数以及您的期望。
标签: c# sql-server-2008 tsql clr user-defined-functions