Как вернуть nvarchar (max) в CLR UDF? - PullRequest
11 голосов
/ 10 декабря 2008

Предполагая следующее определение:

/// <summary>
/// Replaces each occurrence of sPattern in sInput with sReplace. This is done 
/// with the CLR: 
/// new RegEx(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace). 
/// The result of the replacement is the return value.
/// </summary>
[SqlFunction(IsDeterministic = true)]
public static  SqlString FRegexReplace(string sInput, string sPattern, 
      string sReplace)
{
    return new Regex(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace);
}

Передача значения nvarchar(max) для sInput с длиной> 4000 приведет к усечению значения (т. Е. Результат вызова этого UDF равен nvarchar(4000), а не nvarchar(max).

Ответы [ 2 ]

24 голосов
/ 10 декабря 2008

О, как бы там ни было, я сам нашел ответ:

/// <summary>
/// Replaces each occurrence of sPattern in sInput with sReplace. This is done 
/// with the CLR: 
/// new RegEx(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace). 
/// The result of the replacement is the return value.
/// </summary>
[SqlFunction(IsDeterministic = true)]
[return: SqlFacet(MaxSize = -1)]
public static  SqlString FRegexReplace([SqlFacet(MaxSize = -1)]string sInput, 
       string sPattern, string sReplace)
{
    return new Regex(sPattern, RegexOptions.Multiline).Replace(sInput, sReplace);
}

Идея состоит в том, чтобы намекнуть SQL Server, что значения ввода и возврата не являются значениями по умолчанию nvarchar(4000), но имеют другой размер.

Я узнал новый трюк в отношении атрибутов: их можно добавлять к параметрам, а также к самому методу (вполне очевидно), но также к возвращаемому значению с синтаксисом [return: AttributeName(Parameter=Value, ...)].

1 голос
/ 29 июня 2015

См. Также Как создать хранимую процедуру CLR с параметром Nvarchar (max)? , где вы узнаете, как и почему вам действительно следует использовать тип данных SqlChars. Смотри https://msdn.microsoft.com/en-us/library/ms131065.aspx

...