Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

sql - Like operation returns no rows on nvarchar column filter if the column data start with numeric

I have nvarchar(50) column in SQL Server table and data like this:

123abc
234abc
456abc

My query:

select * 
from table 
where col like '%abc'

Expected result : all rows should be returned Actual result: No rows are returned

Works fine if the column is varchar but returns no rows if the type is nvarchar.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You probably have spaces at the end of your data. Take a look at this example.

Declare @Temp Table(col nvarchar(50))

Insert Into @Temp(col) Values(N'123abc')
Insert Into @Temp(col) Values(N'456abc ')

Select * From @Temp Where Col Like '%abc'

When you run the code above, you will only get the 123 row because the 456 row has a space on the end of it.

When you run the code shown below, you will get the data you expect.

Declare @Temp Table(col nvarchar(50))

Insert Into @Temp(col) Values(N'123abc')
Insert Into @Temp(col) Values(N'456abc ')

Select * From @Temp Where rtrim(Col) Like '%abc'

According to the documentation regarding LIKE in books on line (emphasis mine): http://msdn.microsoft.com/en-us/library/ms179859.aspx

Pattern Matching by Using LIKE

LIKE supports ASCII pattern matching and Unicode pattern matching. When all arguments (match_expression, pattern, and escape_character, if present) are ASCII character data types, ASCII pattern matching is performed. If any one of the arguments are of Unicode data type, all arguments are converted to Unicode and Unicode pattern matching is performed. When you use Unicode data (nchar or nvarchar data types) with LIKE, trailing blanks are significant; however, for non-Unicode data, trailing blanks are not significant. Unicode LIKE is compatible with the ISO standard. ASCII LIKE is compatible with earlier versions of SQL Server.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...