如何在CLR UDF中返回nvarchar(max)?

Dar*_*mas 11 c# sql-server clr nvarchar

假设以下定义:

/// <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);
}
Run Code Online (Sandbox Code Playgroud)

在一个传递nvarchar(max)sInput具有长度> 4000将导致被截断的值(即,在调用此UDF的结果是nvarchar(4000)相对于nvarchar(max).

Dar*_*mas 24

哦,无论如何,我自己找到了答案:

/// <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);
}
Run Code Online (Sandbox Code Playgroud)

这个想法是向SQL Server提示输入和返回值不是默认值nvarchar(4000),而是具有不同的大小.

我学习了一个关于属性的新技巧:它们可以添加到参数以及方法本身(非常明显),可以添加到[return: AttributeName(Parameter=Value, ...)]Syntax 的返回值.