简体   繁体   中英

SQL like - select strings that contain unspecified characters

First of all, apologies if this is a duplicate question. I've done my best to search but was unsuccessful, and I couldn't even properly word my question in terms of keywords!

One of my tables has a column Name (nvarchar) . I want to find out which rows contain special characters without explicitly listing those characters. "Special" characters in my case means anything not in:

a-z A-Z 0-9 _ @ . , ( ) % + -

So for example:

Row 1: 'asdf Asdf 0123'
Row 2: 'asdf (Asdf) 012/3'
Row 3: 'zxcv [234]'
Row 4: 'asdf #0123'

I want to select rows 2, 3 and 4.

The easiest way is to include the characters I don't want, for example square brackets and slash:

SELECT * FROM Table
WHERE Name LIKE '%[\]\[/]%' ESCAPE '\'

This returns rows 2 and 3, or if I use NOT LIKE, rows 1 and 4. However, I also want to find other characters which I may not have thought of (such as the #). Listing the characters that ARE wanted -

SELECT * FROM Table
WHERE Name NOT LIKE '%[a-zA-Z0-9_@. ,()%+-]%'

doesn't work either, as it returns 0 results since all rows contain at least 1 of those characters.

Is there a way to restrict the latter LIKE statement not to match any string that contains my desired characters, but rather strings that contain only the desired characters and nothing else?

In MySQL you can do:

WHERE Name REGEX '[^-a-zA-Z0-9.,()%+]'

Not sure if the same REGEX operator exists in SQL Server, but it probably has something similar.

SELECT * FROM tblWHERE PATINDEX('%[^a-zA-Z0-9]%',col) >1

Should return the rows that have non alpha numeric characters. You may need to alter the regex for your specific needs.

use tempdb
create table tbl ( col varchar(40) NULL)

insert into tbl VALUES ('lowercase')
insert into tbl VALUES ('UPPER')
insert into tbl VALUES ('0123')
insert into tbl VALUES ('special characters & ^')
insert into tbl VALUES ('special characters ! \/')
insert into tbl VALUES ('special characters _ + = ')
insert into tbl VALUES (NULL)

SELECT * FROM tbl WHERE PATINDEX('%[^a-zA-Z0-9]%',col) >1

drop table tbl

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