2008-12-10 43 views
11

假設以下定義:如何在CLR UDF中返回nvarchar(max)?

/// <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)

回答

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, ...)]語法返回值。

+0

您是明星,先生:) – 2010-12-14 09:16:58