樣式比對

在 SQL Server 資料庫中清理資料

Miriam Antona

Software Engineer

樣式比對 — 概述

SELECT * FROM series
| id  | name            | contact_number | ... |
|-----|-----------------|----------------|-----|
| 1   | Adventure Time  | 555-906-8845   | ... |
| 2   | Dexter          | 555-156-8845   | ... |
| 3   | Futurama        | 555-210-9951   | ... |
| 4   | Game of Thrones | 555-543-6641   | ... |
| ... | ...             | ...            | ... |
  • 合法號碼:###-###-####
    • 第 1 與第 4 個數字介於 2 到 9
    • 其餘介於 0 到 9
  • 不合法號碼:555-156-8845
在 SQL Server 資料庫中清理資料

樣式比對 — 概述

  • SQL Server 不提供完整的正規表示式功能。
  • SQL Server 可用 LIKE 進行模式比對。
  • 若需完整的正規表示式功能,需建立並安裝擴充套件。
在 SQL Server 資料庫中清理資料

樣式比對 — LIKE

  • 判斷字串是否符合指定樣式
在 SQL Server 資料庫中清理資料

樣式比對 — LIKE

  • 判斷字串是否符合指定樣式
萬用字元 說明 範例
% 任意長度(含 0)的字元串 WHERE contact_number LIKE '555-%'
_(底線) 任意單一字元 WHERE contact_number LIKE '___-___-____'
[] 指定範圍或集合內的任一單一字元 WHERE contact_number LIKE '[2-9][0-9][0-9]-[2-9][0-9][0-9]-[0-9][0-9][0-9][0-9]
[^] 不在指定範圍或集合內的任一單一字元 WHERE contact_number LIKE '[^2-9]'
在 SQL Server 資料庫中清理資料

樣式比對 — % 範例

SELECT name, contact_number
FROM series
WHERE contact_number LIKE '555%'
| name            | contact_number |
|-----------------|----------------|
| Adventure Time  | 555-906-8845   |
| Dexter          | 555-156-8845   |
| Futurama        | 555-210-9951   |
| Game of Thrones | 555-abc-6641   |
| ...             | ...            |
在 SQL Server 資料庫中清理資料

樣式比對 — % 範例

SELECT 
    name, 
    contact_number
FROM series
WHERE contact_number NOT LIKE '555%'
| name            | contact_number |
|-----------------|----------------|
| The Good Doctor | 000-930-1274   |
在 SQL Server 資料庫中清理資料

樣式比對 — [](中括號)範例

SELECT 
    name, 
    contact_number
FROM series
WHERE contact_number LIKE '[2-9][0-9][0-9]-[2-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'
| name           | contact_number |
|----------------|----------------|
| Adventure Time | 555-906-8845   |
| Futurama       | 555-210-9951   |
| Homeland       | 555-985-6314   |
| Westworld      | 555-456-1234   |
| ...            | ...            |
在 SQL Server 資料庫中清理資料

樣式比對 — [](中括號)範例

SELECT 
    name, 
    contact_number
FROM series
WHERE contact_number NOT LIKE '[2-9][0-9][0-9]-[2-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'
| name            | contact_number |
|-----------------|----------------|
| Dexter          | 555-156-8845   |
| Game of Thrones | 555-abc-6641   |
| The Good Doctor | 000-930-1274   |
在 SQL Server 資料庫中清理資料

一起來練習吧!

在 SQL Server 資料庫中清理資料

Preparing Video For Download...