简体   繁体   中英

SQL How to search text field for 2nd without matching 22nd, etc?

我想查询可以出现在文本列中任何位置的编号街道名称,并过滤掉具有更多数字的编号街道名称的匹配项,即2nd但不是42nd182nd等。 有没有比组合更优雅或简化的方法:

WHERE col LIKE '2nd%' OR col LIKE '% 2nd%'

As long as the 2nd doesn't occur at the beginning of the string, you can just check that the character before it is not a digit using

col LIKE '%[^0-9]2nd%'

For example:

select col, case when  col like '%[^0-9]2nd%' then 'second' else 'not' end as test
from (values ('12 2nd st'), ('45 42nd st'), ('128 22nd st')) test(col)

Output:

col             test
12 2nd st       second
45 42nd st      not
128 22nd st     not

Nick's answer is very good, but it doesn't handle the case when '2nd' appears at the beginning of a string. This is easily handled by pre-pending a character on the column being compared:

' ' + col LIKE '%[^0-9]2nd%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM