在這回中將探討SQL server中like的使用方式。
Like
like被用在SQL語法中的where條件。
用來篩選模糊字串。
通常搭配這兩種運算子去實作模糊搜尋條件。
% 代表零或一個或更多的字符
_ 代表一個字符
語法:
1 | SELECT column1, column2, ... |
常見的模糊字串操作:
LIKE Operator | Description |
---|---|
WHERE CustomerName LIKE 'a%' | Finds any values that start with "a" |
WHERE CustomerName LIKE '%a' | Finds any values that end with "a" |
WHERE CustomerName LIKE '%or%' | Finds any values that have "or" in any position |
WHERE CustomerName LIKE '_r%' | Finds any values that have "r" in the second position |
WHERE CustomerName LIKE 'a_%' | Finds any values that start with "a" and are at least 2 characters in length |
WHERE CustomerName LIKE 'a__%' | Finds any values that start with "a" and are at least 3 characters in length |
WHERE ContactName LIKE 'a%o' | Finds any values that start with "a" and ends with "o" |
範例實作
customers 顧客
products 產品
orders 出貨單
order_details 出貨單明細
實作:想取得產品名稱為P開頭的產品。
1 | Select * from products where name like 'P%' |
結果:
實作:實作訂單收或簽名為「X中間有一個字X」的人
1 | Select * from orders where orders.customer_signature like 'X_X' |
結果:
可得到XXX這個人的訂單明細。因為他X與X間隔一個字符。
結論
可以用like在資料庫內做簡易的模糊比對,將一些無法直接對應的數值用這種方式去篩選。