简体   繁体   中英

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'

When querying the table using testcolumn like '%17KA%' no results are returned. If I query using '%17KAA%' I do get a result.

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

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

Try and see if adding N before your pattern (mark it as Unicode) makes any difference. 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.

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

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". So you cannot search for it as just an "A".

The reason is that "AA" is a way of representing Å.

So, your code is working correctly. You can convert to a different collation where 'AA' is just 'A' following 'A' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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