gpt4 book ai didi

c# - 具有默认列名的sql server CLR标量函数

转载 作者:太空狗 更新时间:2023-10-29 20:27:53 26 4
gpt4 key购买 nike

我想知道是否有任何方法可以将列名添加到我在 Sql Server 中的 CLR 标量函数中。我的意思是,在我运行查询之后,我希望看到一个包含此函数结果的列,该列已使用自定义名称而不是 (No column name) 命名。

我知道函数经常组合在一起,或者出于其他原因我不得不给它们起不同的名字,但仍然 - 当您编写包含 30 列的查询时,不必为其中的 20 列输入别名做个好人。

那么有人知道可以实现这一点的黑客吗?

通过 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

结果已经有了列名,无需在T-SQL中添加别名: enter image description here

最佳答案

答案是“不”。标量函数(无论是否为 CLR)仅返回一个值。

“用户定义的标量函数返回 RETURNS 子句中定义的类型的单个数据值。”每MSDN

正如您所建议的,正确的解决方案是在您使用该函数的地方添加一个别名。

SELECT ABS(a.Position - b.Position) AS Distance
FROM sch.Tbl a
INNER JOIN sch.Tbl b
ON a.Key <= b.Key
;

这不会改变函数是内置函数、用户定义函数还是 CLR 函数。

关于c# - 具有默认列名的sql server CLR标量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16402513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com