SQL LIKE运算符在应该没有显示任何结果时

时间:2013-01-30 08:53:46

标签: sql sql-server tsql sql-like

我有一个包含大量信息的Vehicle表,但其中一列是MSSQL表中的'Owner'

但其中一位所有者在我使用LIKE时无法选择,但如果我使用=

'Silkeborg Distributionscenter'是所有者(是的,表格和参数中都有一个双重空格)

所以参数是:

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

我试过了:

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

然后:

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

然后:

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

我需要使用LIKE,因为我需要能够一次选择所有者数组。所以原始的select语句看起来像这样

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

任何想法?

修改 这一切都很好@Owners是'Fredericia Distributionscenter'而不是'Silkeborg Distributionscenter',它们都在桌面上。

这些内容是否适用于'Silkeborg Distributionscenter'文本?

5 个答案:

答案 0 :(得分:5)

根据要求提升答案。

在Vehicle表的Owner字段末尾有一些空格字符。 '='运算符跳过尾随空格,'like'运算符不跳过。

答案 1 :(得分:3)

尝试交换列和参数

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

答案 2 :(得分:2)

以下运行正常,我怀疑缺少信息

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

仍可使用

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

但如果

则失败
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

答案 3 :(得分:1)

您的查询不正确。写得像:

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

答案 4 :(得分:0)

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

SELECT * 
FROM   Vehicle 
WHERE  Owner LIKE @Owners

或者您也可以传递一个修改过的参数,这是从前端传递参数时使用的