C#中的字符编码和SQL

Char encoding and SQL in C#

我有这个 sql:

select productid from products where productcode = @code

和@code 是一个参数,它的值是 ABCÊ 但它匹配 ABC 调试它在 visual studio 中显示 � 在 quickwatch 中。数据库有 Latin1_General_CI_AS 作为排序规则。数据库中的字段类型是nvarchar(50)

那么,当我将它与 ABCÊ 进行比较时,为什么包含 productcode = 'ABC' return 的数据行被编辑了? 我在我的 smss select 1 where 'ABC' = 'ABCÊ' 中输入了这个,但它没有 return 1,这是:select 1 其中 'ABC' = 'ABC' 那么它在我的代码中吗? utf 或编码的东西?

编辑 c#代码:

SqlCommand comGetProd = new SqlCommand(@"SELECT ProductID FROM PRODUCTS WHERE (ProductCode = @name)");
comGetProd.Parameters.AddWithValue("name", "ABCÊ");

编辑 2015 年 6 月 15 日

按照@Oskar Sjöberg 的建议缩小了问题范围。它与数据库无关!因为这个 returns true:

using (StreamReader sr = new StreamReader("test.csv"))
{
    while (!sr.EndOfStream)
    {                  
        Console.WriteLine("D1103SL".Equals(sr.ReadLine()));
    }
}

test.csv 包含:D1103SLÊ

记事本++:

原来如此http://www.codetable.net/hex/ca我还是不明白怎么相等。

使用

COLLATE DATABASE_DEFAULT

喜欢下面

select productid from products where productcode COLLATE DATABASE_DEFAULT = @code

尝试使用 SQL_Latin1_General_CP1_CI_AS 而不是 COLLATE Latin1_General_CI_ASsource

如果您使用的是 LINQ,则可以使用区域性比较。

var result = from a in collection.Products
             select a.Productid
             where string.Equals(a.ProductCode, 'ABCÊ', StringComparison.Ordinal);

我尝试使用相同的排序规则设置相同的场景,table 和示例数据以及 运行 此代码:

var connection = new SqlConnection("connectionstringgoeshere");
connection.Open();
var command = new SqlCommand(@"SELECT ProductID FROM PRODUCTS WHERE (ProductCode = @name)", connection);
command.Parameters.AddWithValue("name", "ABCÊ");
var dataTable = new DataTable();
dataTable.Load(command.ExecuteReader());
Console.WriteLine(dataTable.Rows);  

它 returns 按预期归零行,并将代码中的 "ABCÊ" 更改为 "ABC" returns 一行,其中包含正确的数据。

我认为这里还有另一个问题,但您需要包含一个更完整但仍然是最小的代码示例、数据库模式和数据库数据。

Apparently, "\xCA" is a non-breaking space on the Mac — the same as "\xA0" on Windows and in ISO-Latin-1, and " " in HTML.

http://use.perl.org/use.perl.org/commentsf6b4-3.html?sid=18447&op=reply&threshold=0&commentsort=0&mode=thread

所以当使用UTF-8编码时,它只知道这是一个无意义的字符,可以跳过,所以字符串是相等的

using (StreamReader sr = new StreamReader("test.csv", ASCIIEncoding.UTF8))
{
    while (!sr.EndOfStream)
    {
        Console.WriteLine("D1103SL".Equals(sr.ReadLine()));
    }
}

并且当使用 ascii 时,它 'sees' Ê 并且当比较时,它 returns 假。