简体   繁体   English

SQL 服务器查询中的 Like 语句未返回所有结果

[英]Like statement in SQL Server query not returning all results

I have a database table with a column of type nvarchar(max) and the value '17KAAKSPN13'我有一个数据库表,其中有一列类型为nvarchar(max) ,值为 '17KAAKSPN13'

When querying the table using testcolumn like '%17KA%' no results are returned.使用像 '%17KA%' 这样的 testcolumn 查询表时,不会返回任何结果。 If I query using '%17KAA%' I do get a result.如果我使用 '%17KAA%' 进行查询,我会得到一个结果。

To test this, create a simple table and perform the queries below and see that the second query does not return any results:要对此进行测试,请创建一个简单的表并执行以下查询,然后查看第二个查询没有返回任何结果:

Update: Server collation: Danish_Norwegian_CI_AS更新:服务器排序规则:Danish_Norwegian_CI_AS

CREATE TABLE [dbo].testtable(
    testcolumn [nvarchar](max) NULL
) 

insert into [dbo].testtable (testcolumn) values('17KAAKSPN13')

SELECT * FROM [dbo].testtable 
SELECT * FROM [dbo].testtable WHERE testcolumn like '%17KA%'

Result:结果:使用like查询时没有返回结果

EDIT:编辑:

Here is an example of it not working. 是它不起作用的示例。 I'm adding this as an edit because there are many comments and two inappropriate fiddles.我将其添加为编辑,因为有很多评论和两个不合适的小提琴。 The issue seems to have to do with collation.这个问题似乎与整理有关。

Coming from here - https://stackoverflow.com/a/53802337/13927312来自这里 - https://stackoverflow.com/a/53802337/13927312

Try and see if adding N before your pattern (mark it as Unicode) makes any difference.尝试看看在您的模式之前添加 N(将其标记为 Unicode)是否有任何区别。 It might not explain this behavior but can solve your problem.它可能无法解释这种行为,但可以解决您的问题。

SELECT * FROM [dbo].testtable WHERE testcolumn like N'%17KA%'

you can go for COLLATE clause to convert into a collation, which makes the LIKE to work out.您可以将 COLLATE 子句的 go 转换为排序规则,这使得LIKE可以解决。

SELECT * FROM [dbo].testtable WHERE testcolumn collate SQL_Latin1_General_CP1_CI_AS 
like '%17KA%' collate SQL_Latin1_General_CP1_CI_AS 

From MSDN on collation 来自 MSDN 上的整理

Character literals and variables are assigned the default collation of the current database.字符文字和变量被分配了当前数据库的默认排序规则。 Column references are assigned the definition collation of the column.列引用被分配列的定义排序规则。

I think the issue is that in Norwegian and Danish, "AA" is a different character from "A".我认为问题在于在挪威语和丹麦语中,“AA”与“A”是不同的字符。 So you cannot search for it as just an "A".因此,您不能仅将其搜索为“A”。

The reason is that "AA" is a way of representing Å.原因是“AA”是代表Å的一种方式。

So, your code is working correctly.因此,您的代码工作正常。 You can convert to a different collation where 'AA' is just 'A' following 'A' .您可以转换为不同的排序规则,其中'AA'只是'A'跟在'A'之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM