我想知道,是否有任何方法可以在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中添加别名:
答案 0 :(得分:3)
答案是“不”标量函数(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函数。
答案 1 :(得分:2)
我假设某个地方你有这样的话:
command.CommandText = "SELECT SomeFunction();";
试试这个
command.CommandText = "SELECT SomeFunction() 'AliasForColumnNameYouWant';";
不确定20或30个函数的含义是什么?
你是说在Sql-Server中有一些存储过程或函数调用20或30个不同的标量函数?
或者相同的功能被称为20或30次?
您是否将结果合并到可退回的行或数据列中?
请提供代码示例。