2017-02-22 89 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 '\' 

引用感謝大家的幫助

相關問題