我正在使用sql clr应用程序,在与sql集成之后,我收到此错误(对于英语它正在工作但在将Unicodes添加到词典时出现问题):
**Msg 6522, Level 16, State 2, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "SqlCompare":
System.ArgumentException: An item with the same key has already been added.
System.ArgumentException:
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at Translate_Class_NUM..ctor()
at StringPercentageCompare..ctor()
at UserDefinedFunctions.SqlComparison()**
here is my code in c#
private Dictionary<string, string> MyDictionary;
//private string[,] MyArray;
public Translate_Class_NUM()
{
MyDictionary.Add("?", "01");
MyDictionary.Add("?", "02");
MyDictionary.Add("?", "03");
MyDictionary.Add("?", "04");
MyDictionary.Add("?", "05")
}
并在sql server代码中 CREATE ASSEMBLY DBDB_DeDuplication 授权dbo 来自&E; \ Projects \ DBDB_DeDuplication \ DBDB_DeDuplication \ obj \ Debug \ DBDB_DeDuplication.dll&#39; WITH PERMISSION_SET =安全 GO
CREATE FUNCTION SqlCompare()RETURNS nvarchar(50) 作为外部名称DBDB_DeDuplication.UserDefinedFunctions.SqlComparison; GO
SELECT dbo.SqlCompare(); GO
提前致谢
答案 0 :(得分:2)
这段代码对我来说很合适:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("ಅ","01");
dict.Add("ಇ","02");
正如我之前在评论中尝试解释的那样,您的Unicode字符串不能以您期望的方式传递给编译器。有时这可能是由于使用ASCII编码或其他非Unicode支持编码保存的C#源文件。要保证结果,请使用C#Unicode文字编码(U + 0000到U + FFFF)。
如果您不知道如何获得等效的Unicode转义序列,则可以使用以下代码:
static string EncodeNonAsciiCharacters( string value )
{
StringBuilder sb = new StringBuilder();
foreach( char c in value ) {
if( c > 127 ) {
// This character is too big for ASCII
string encodedValue = "\\u" + ((int) c).ToString( "x4" );
sb.Append( encodedValue );
}
else {
sb.Append( c );
}
}
return sb.ToString();
}
Console.WriteLine(EncodeNonAsciiCharacters("ಅ"));
\u0c85
Console.WriteLine(EncodeNonAsciiCharacters("ಇ"));
\u0c87
那么您可以将更安全版本的源代码编写为:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("\u0c85","01");
dict.Add("\u0c87","02");