SQL Server SQL - NOT LIKE and LIKE with only characters

zpjtge22  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(103)

I am learning SQL(without concrete implementation).

I need to validate that some value contains only characters using LIKE or NOT LIKE

1.Incorrect example is:

SELECT * FROM table WHERE name LIKE '%[a-zA-Z]'

because '123A123' would be true

2. I read up that It would work

SELECT * FROM table WHERE name NOT LIKE '%[^a-zA-Z]%'

These queries look equal to me(It's like to compare 5 and --5)

Could you explain please what is the difference between?

fhg3lkii

fhg3lkii1#

Ok, let's dissect this:

NOT LIKE '%[^a-zA-Z]%'

The regexp here is "does not contain any letters". If we negate using NOT LIKE , it'll mean "contains only letters".

Now:

name LIKE '%[A-Za-z]%'

Regexp here means "contains at least one letter". So LIKE on that will mean the same thing.

So:

SELECT * FROM (VALUES ('A123'), ('123'), ('AAA'), (',')) x(name)
WHERE name LIKE'%[A-Za-z]%'

This will return both A123 (there's an A) and AAA , but neither 123 (only digits) nor , (still not a letter) will get returned.

SELECT * FROM (VALUES ('A123'), ('123'), ('AAA'), (',')) x(name)
WHERE name NOT LIKE '%[^A-Za-z]%'

This one will only return AAA because it's the only one containing letters only. AAA is the only record that regexp will not match, and since we're negating with NOT LIKE , it means only this one meets the WHERE condition.

wqlqzqxt

wqlqzqxt2#

This expression:

WHERE name NOT LIKE '%[^a-zA-Z]%'

matches all names that have a character that is not a letter, such as . or ; or whatever.

This expression:

name LIKE '%[a-zA-Z]'

matches all names that contain at least one letter.

So, 'ABC.DEF' will match both patterns -- it matches the first because it has . and the second because it has a letter.

However, 'ABC' does not match the first pattern because it only consists of letters. It does match the second one.

qqrboqgw

qqrboqgw3#

Following condition will check whether your column value has any string character from a-z or A-Z in it.

where name NOT REGEXP '[a-zA-Z]'

相关问题