简体   繁体   English

类似SQL-选择包含未指定字符的字符串

[英]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) . 我的一张桌子有一列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. 我想选择第2、3和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 #). 这将返回第2行和第3行,或者如果我使用NOT LIKE,则返回第1行和第4行。但是,我还想找到其他我可能没有想到的字符(例如#)。 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. 也不起作用,因为它返回0个结果,因为所有行都至少包含这些字符中的1个。

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? 有没有一种方法可以限制后面的LIKE语句不匹配包含我想要的字符的任何字符串,而是匹配包含想要的字符而没有其他内容的字符串?

In MySQL you can do: 在MySQL中,您可以执行以下操作:

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

Not sure if the same REGEX operator exists in SQL Server, but it probably has something similar. 不知道SQL Server中是否存在相同的REGEX运算符,但它可能具有相似的含义。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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