乙個關於模糊查詢的寫法

2021-04-12 21:22:55 字數 2080 閱讀 1258

今天在論壇上看到這樣一帖:

share欄位是varchar型別的,裡面存放的資料是『1,2,24』格式的

現在我要找出該字段中所有包含1,2,3,4四個數字中任一數值的記錄。

我最初的寫法:db.dbcmd.commandtext = "select * from userinfo where share like '%1%' or username like '%2%' or username like '%3%' or username like '%4%' "

別人的寫法:db.dbcmd.commandtext = "select * from userinfo where share like '%[1-4]%'  "我順便學習了一下,寫在這裡。。。。。。回味一下!

**********************************以下內容是有關模糊查詢的網上**資料*******************************

其中關於條件,sql提供了四種匹配模式:

1,%:表示任意0個或多個字元。可匹配任意型別和長度的字元,

有些情況下若是中文,請使用兩個百分號(%%)表示。

比如 select * from [user] where u_name like '%三%'

將會把u_name為「張三」,「張貓三」、「三腳貓」,「唐三藏」等等有「三」的記錄全找出來。

另外,如果需要找出u_name中既有「三」又有「貓」的記錄,請使用and條件

select * from [user] where u_name like '%三%' and u_name like '%貓%'

若使用

select * from [user] where u_name like '%三%貓%'

雖然能搜尋出「三腳貓」,但不能搜尋出符合條件的「張貓三」。

2,_: 表示任意單個字元。匹配單個任意字元,它常用來限制表示式的字元長度語句:

比如 select * from [user] where u_name like '_三_'

只找出「唐三藏」這樣u_name為三個字且中間乙個字是「三」的;

再比如 select * from [user] where u_name like '三__';

只找出「三腳貓」這樣name為三個字且第乙個字是「三」的;

3,[ ]:表示括號內所列字元中的乙個(類似正規表示式)。指定乙個字元、字串或範圍,要求所匹配物件為它們中的任乙個。

比如 select * from [user] where u_name like '[張李王]三'

將找出「張三」、「李三」、「王三」(而不是「張李王三」);

如 [ ] 內有一系列字元(01234、abcde之類的)則可略寫為「0-4」、「a-e」

select * from [user] where u_name like '老[1-9]'

將找出「老1」、「老2」、……、「老9」;

4,[^ ]:表示不在括號所列之內的單個字元。其取值和 相同,但它要求所匹配物件為指定字元以外的任乙個字元。

比如 select * from [user] where u_name like '[^張李王]三'

將找出不姓「張」、「李」、「王」的「趙三」、「孫三」等;

select * from [user] where u_name like '老[^1-4]';

將排除「老1」到「老4」,尋找「老5」、「老6」、……

5,查詢內容包含萬用字元時

由於萬用字元的緣故,導致我們查詢特殊字元「%」、「_」、「[」的語句無法正常實現,而把特殊字元用「[ ]」括起便可正常查詢。據此我們寫出以下函式:

function sqlencode(str)

str=replace(str,"[","[") '此句一定要在最前

str=replace(str,"_","[_]")

str=replace(str,"%","[%]")

sqlencode=str

end function

在查詢前將待查字串先經該函式處理即可。

獲取乙個模糊查詢

set ansi nulls on set quoted identifier on goalter function dbo getfirstalpha str nvarchar 4000 returns nvarchar 4000 asbegin declare strlen int,re nv...

關於乙個sql的寫法

需求是這樣的 有個學生表 create table student id int primary key,name varchar2 200 有個成績表 create table score id int 對應與student 的 id 僅為測試,表結構也沒好好設計 math int,eng int...

linux如何模糊查詢乙個檔案

linux如何模糊查詢乙個檔案 在當前目錄下搜尋指定檔案 find name test.txt 在當前目錄下模糊搜尋檔案 find name txt 在當前目錄下搜尋特定屬性的檔案 find amin 10 查詢在系統中最後10分鐘訪問的檔案 find atime 2 查詢在系統中最後48小時訪問的...