SQL LIKE operator not showing any result when it should

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-19 12:54:34

问题


I got a Vehicle table with lots of info but one of the columns being 'Owner' in a MSSQL table

But one of the owners i can't select when i use LIKE but can if i use =

'Silkeborg Distributionscenter' is the owner (Yes there is a double space in both the table and the param)

So the param is:

DECLARE @Owners nvarchar(MAX) = 'Silkeborg  Distributionscenter'

I tried:

SELECT * FROM Vehicle WHERE @Owners = Owner 
--This gave me all the correct results

Then:

SELECT * FROM Vehicle WHERE @Owners LIKE Owner
--No result

Then:

SELECT * FROM Vehicle WHERE @Owners COLLATE Danish_Norwegian_CI_AS LIKE Owner COLLATE Danish_Norwegian_CI_AS
--No result

I need to use LIKE because i need to be able to select a array of owners at once. So the original select statement look like this

SELECT * FROM Vehicle WHERE ('|' + @Owners + '|' like '%|' + Owner + '|%')
--No result

Any Ideas?

Edit: It all works fine the @Owners is 'Fredericia Distributionscenter' but not 'Silkeborg Distributionscenter', Both of them is within the table.

Is the something work in the 'Silkeborg Distributionscenter' text?


回答1:


Promoted to an answer as requested.

You have some space characters in the end of your Owner field in Vehicle table. '=' operator skips trailing spaces, 'like' operator doesn't.




回答2:


try interchanging the column and the parameter

SELECT * 
FROM   Vehicle 
WHERE  Owner LIKE '%' + @Owners + '%'



回答3:


the following runs fine, I suspect a missing information

declare @t  table (
    owner nvarchar(50)
)

insert into @t values ('Silkeborg  Distributionscenter'), ('rzrzezer')

declare @owner nvarchar(max) = 'Silkeborg  Distributionscenter'

select * from @t
-- two lines
select * from @t where @owner = owner
-- one line
select * from @t where @owner like owner
-- one line

still works with

set @owner = 'Silkeborg  Distributionscenter|another one'
select * from @t where '|' + @owner + '|'  like '%|' + owner + '|%'
-- one line

but fail if

insert into @t values ('Silkeborg  Distributionscenter|abc')
select * from @t where '|' + @owner + '|'  like '%|' + owner + '|%'
-- one line, you may expect 2 in this case consider using a many to many relation



回答4:


Your query is incorrect. Write it like:

SELECT * FROM Vehicle WHERE Owners like '%' + @Owners + '%'



回答5:


DECLARE @Owners nvarchar(MAX) = '%Silkeborg  Distributionscenter%'

SELECT * 
FROM   Vehicle 
WHERE  Owner LIKE @Owners

Or you can pass a modified param too, this of use when passing params from front end



来源:https://stackoverflow.com/questions/14599990/sql-like-operator-not-showing-any-result-when-it-should

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!