2017-02-22 125 views
1

我很确定有人已经有这个问题,但我不知道如何写入。sql server部分字符串搜索

在我的SQL Server数据库

,我试图寻找其中Field1包含ABC的记录,但不ABC [德]

因此以下记录将被发现

'123abc222'

“ ABC”

下面的记录将不会被发现

'123ABC [德]'

我知道

'abc123abc [de]'很棘手,但我现在不必担心。

很多人会问,为什么我要执行这个搜索,而不是改变程序,数据库等。这就是问题所在。程序处于稳定状态的问题。增加一个额外的领域几乎是不可能的。我们团队想要引入更多问题的最后一件事。是的,添加额外的列或修改数据库设计是更好的,但是,像大多数现实世界中的应用,我们只是想最小改变现有的应用程序

感谢

回答

2
select * 
from t 
where field1 like '%abc%' 
    and field1 not like '%abcde%' 

测试设置:http://rextester.com/ZZTZ72327

create table t (
    id int identity(1,1) 
    , field1 varchar(32) not null 
); 
insert into t values 
('123abc222') 
,('123abcde'); 

查询:

select * 
from t 
where field1 like '%abc%' 
    and field1 not like '%abcde%' 

结果:

+----+-----------+ 
| id | field1 | 
+----+-----------+ 
| 1 | 123abc222 | 
+----+-----------+ 
+0

我试过了,但它仍然检索“123ABCDE” – user12345

+0

@ user12345你在使用'或'的'where'中有附加标准,但没有正确包装在括号中? – SqlZim

+0

这就是我想要辩论的。最糟糕的是,我不得不在asp.net上添加一列和一个控件。这是我的最后一个选项 – user12345

2

使用likenot like

where col like '%abc%' and col not like '%abcde%' 
1

喜欢的东西:

select * from table where field like 'abc%' and field not like '%def%';

+0

它没有检索到任何东西 – user12345

0

如何用空字符替换所有数字则只是比较结果使用'='比较器。

SELECT * 
FROM table 
WHERE field = REPLACE(REPLACE(REPLACE(REPLACE(
     REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
     REPLACE(@str, '0', ''),'1', ''),'2', ''), 
     '3', ''),'4', ''),'5', ''),'6', ''),'7', 
     ''),'8', ''),'9', '') 

这将使您只有字母字符。

1

谢谢大家的回答。这是我的错,我没有效仿的问题正确

从JCE和SqlZim

select * 
from t 
where field1 like '%abc%' 
    and field1 not like '%\[abcde]%' ESCAPE '\' 

引用感谢大家的帮助