2008年10月21日 星期二

使用REGEX 查詢資料庫

我想從資料庫中查有關A開頭資料,要怎麼查呢?
比較笨的寫法可能是如下

select * from tabel where name like '3%'

那我的條件改為A開頭K結尾那要怎麼下呢?

select * from tabel where name like '3%' and name like '%K'

如果我的條件又變為A開頭,第三、四個字是45,然後K結尾呢?光想就很麻煩了
所以如果對Regex熟悉的話,用可以很方便的用正規化來查詢相關資料

select * from tabel where REGEXP_LIKE (name,'^A.45.*K$')//Oracle
select * from tabel where name REGEXP '^A.45.*K$'//MySql
select * from tabel where dbo.RegexMatch (name,'^A.45.*K$')//SqlServer


底下相關的資料連結
http://www.psoug.org/reference/regexp.html
http://www.regular-expressions.info/mysql.html
http://msdn.microsoft.com/en-us/magazine/cc163473.aspx