喜欢在SQL Server中使用特殊chracher进行搜索
嗨,我有一张桌子喜欢在SQL Server中使用特殊chracher进行搜索,sql,sql-server,Sql,Sql Server,嗨,我有一张桌子tbl\u Main AS_ID KWD 1 Man,Businessman,[Business],Office,confidence,arms crossed, 2 Man,Businessman,Business,[Office],laptop,"corridor",waiting, 3 man,business,mobile phone,[mobile],"phone", 如果我用like搜索[office],我没有得到任何结果 我
tbl\u Main
AS_ID KWD
1 Man,Businessman,[Business],Office,confidence,arms crossed,
2 Man,Businessman,Business,[Office],laptop,"corridor",waiting,
3 man,business,mobile phone,[mobile],"phone",
如果我用like搜索[office]
,我没有得到任何结果
我正在使用以下查询
select * from tbl_main where KWD like '%,[Office],%'
请帮助我解决此查询。谢谢尝试此操作
select * from tbl_main where KWD like '%,[Office],%'
[
和]
在SQL Server中使用类似于的时用于模式匹配(类似于regex),因此您实际搜索的是
WHERE KWD LIKE '%,O,%'
OR KWD LIKE '%,f,%'
OR KWD LIKE '%,i,%'
OR KWD LIKE '%,c,%'
OR KWD LIKE '%,e,%'
您需要避开括号,例如:
SELECT *
FROM (VALUES
(1, 'Man,Businessman,[Business],Office,confidence,arms crossed,'),
(2, 'Man,Businessman,Business,[Office],laptop,"corridor",waiting,'),
(3, 'man,business,mobile phone,[mobile],"phone",')
) t (AS_ID, KWD)
WHERE KWD like '%,\[Office\],%' ESCAPE '\';
附录
为了使数据正常化,您应该使用一个单独的关系表,将外键返回到tbl_main
,而不是存储分隔列表
AS_ID Keyword
-----------------------
1 Man
1 Businessman
1 [Business]
1 Office
1 confidence
1 arms crossed
现在,您有了一个简单的查询,可以利用索引的使用(如果存在):
SELECT *
FROM ASKeyword
WHERE Keyword = '[Office]';
您正在尝试查询没有Office的AS_ID。尝试查询KWD for Office。@Gitz我已更新了我的答案。使用相同的查询但没有得到任何结果,“phone”应该正常工作--其中KWD类似“%”、“phone”和“%”
感谢您的帮助@GarethD:)我正在使用类似搜索查询之间的周界,例如“%”、\[+@KWD+'\]、“%”ESCAPE'\\'”
,但没有得到任何结果@Garethdy您应该替换参数-中的特殊字符,其中KWD类似“%”、“+replace(replace(replace(@KWD、“\\”、“\\”、“]'、“\]')、“[”、“\[”)+”、“%”转义“\”