2015-07-03 79 views
3

我想只返回包含特定字段中的文本[XXXX]的值。 我的查询返回有4位数字的值,因为我假设SQL服务器将[XXXX]视为任何具有4位数字的数字。SQL Server - LIKE [XXXX]

我有一个测试查询下面的值列表来演示这个问题。

select X.VadDesc 
From (VALUES 
('Product AAAA Description'), 
('Product BBBB Description'), 
('Product [XXXX] Description'), 
('Product2 [XXXX] Description'), 
('Product 2 [AAAA] Description'), 
('Product X 1234 Description'), 
('Product X 1235 Description'), 
('Product X 1236 Description'), 
('Product X 1237 Description') 
) as X (VadDesc) 
Where X.VadDesc like '%[XXXX]%' 

我的查询应该只返回:

Product [XXXX] Description 
Product2 [XXXX] Description 

但它返回:

Product [XXXX] Description 
Product2 [XXXX] Description 
Product X 1234 Description 
Product X 1235 Description 
Product X 1236 Description 
Product X 1237 Description 

我怎样才能做到这一点? 我不只是想寻找XXXX,因为这可能是我不想返回的行。

+0

'[ABC]'是字符范围。这意味着该模式应该与任何字符A,B,C匹配。你需要逃避[ –

回答

4
select X.VadDesc 
From (VALUES 
('Product AAAA Description'), 
('Product BBBB Description'), 
('Product [XXXX] Description'), 
('Product2 [XXXX] Description'), 
('Product 2 [AAAA] Description'), 
('Product X 1234 Description'), 
('Product X 1235 Description'), 
('Product X 1236 Description'), 
('Product X 1237 Description') 
) as X (VadDesc) 
Where X.VadDesc like '%[[]XXXX]%' 
+0

有一点需要注意的是,这种情况也会得到'Product [XX [] XXX]'的产品说明' – ughai

+1

正确的方法是'[[] XXXX]'。所有学分[@MartinSmith](http://stackoverflow.com/users/73226/martin-smith) – ughai

+0

是的正确。我正在为此而努力。在答案中添加。谢谢@ughai。 –

5

使用Escape character转义[像这样'%\[XXXX\]%' {escape '\'}

查询

select X.VadDesc 
From (VALUES 
('Product AAAA Description'), 
('Product BBBB Description'), 
('Product [XXXX] Description'), 
('Product2 [XXXX] Description'), 
('Product 2 [AAAA] Description'), 
('Product X 1234 Description'), 
('Product X 1235 Description'), 
('Product X 1236 Description'), 
('Product X 1237 Description') 
) as X (VadDesc) 
Where X.VadDesc like '%\[XXXX\]%' {escape '\'} 

SQL Fiddle

+0

]不要打扰问,有些人只是喜欢随机答案,更好地让它离开 – Lamak

+0

谁低估可能不知道你可以在'LIKE'中指定你自己的转义字符。另一个正确的答案也得到了一个downvote –

+0

@Lamak - 我更愿意问,所以如果有一个正当的理由,我可以改善我的答案,并在过程中学习新东西。看起来这不是其中之一。 – ughai