簡體   English   中英

具有默認列名的sql server CLR標量函數

[英]sql server CLR scalar function with default column name

我想知道,是否有任何方法可以將列名添加到 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

Result 已經有了列名,無需在 T-SQL 中添加別名:在此處輸入圖像描述

答案是不。” 標量函數(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函數。

我假設某個地方你有這樣的事情:

command.CommandText = "SELECT SomeFunction();";

嘗試這個

command.CommandText = "SELECT SomeFunction() 'AliasForColumnNameYouWant';";

不確定20或30個函數的含義是什么?

你是說在Sql-Server中有一些存儲過程或函數調用20或30個不同的標量函數?

或者相同的功能被稱為20或30次?

您是否將結果合並到可返回的行或數據列中?

需要代碼示例。

標量函數可以看作是表達式的等價物,SQL 不請求作為表達式乘積返回的列的名稱。 在 SQL 中,如果你想返回一個帶有列名的表達式,你必須用以下兩種方式中的任何一種來給它起別名:

Select MyCol=Substring('123',2,1)

或者

Select Substring('123',2,1) as MyCol

如果您想在查詢中的其他一些地方重用別名來構建另一個表達式(我更喜歡 Alias=Expression)

Select MyExp2=MyExp+'2', MyExp3=MyExp+3, MyExp4
From 
  SomeTable
  CROSS APPLY (Select MyExp=Substring(SomeTable.SomeCol, 2, 1)) as MyExp
  -- below an example of reusing MyExp in another apply
  CROSS APPLY (Select MyExp4= MyExp + Substring(SomeTable.SomeCol, 4, 1)) as MyExp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM