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

时间:2008-12-10 15:04:23

标签: 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);
}

传递长度为&gt; nvarchar(max)的{​​{1}}值4000将导致值被截断(即调用此UDF的结果为sInput而不是nvarchar(4000)

2 个答案:

答案 0 :(得分: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);
}

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

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

答案 1 :(得分:1)

另请参阅How to create CLR stored procedure with Nvarchar(max) parameter?,了解您应该如何/为何真正使用SqlChars数据类型。见https://msdn.microsoft.com/en-us/library/ms131065.aspx

免费获取贴纸的机会↓↓↓
豫ICP备18024241号-1