SQL REPLACE 函式

摘要:在本教程中,您將學習如何使用 SQL REPLACE 函式將字串中所有出現的子字串替換為另一個子字串。

SQL REPLACE 函式簡介 #

在 SQL 中,REPLACE() 函式用於將字串中所有出現的子字串替換為一個新的子字串。

以下是 REPLACE 函式的語法:

REPLACE(string, search_string, replacement_string);Code language: SQL (Structured Query Language) (sql)

REPLACE() 函式接受三個引數:

  • string:您希望在其中替換所有子字串的字串。
  • search_string:您想要替換的子字串。
  • replacement_string:您希望用來替換 search_string 的新子字串。

REPLACE 函式返回一個新字串,其中所有出現的 search_substring 都被 replacement_string 替換。

在實踐中,您會發現 REPLACE() 函式在查詢中替換字串或更新表中的資料時非常有用。

基本的 REPLACE 函式示例 #

以下語句使用 REPLACE() 函式將所有出現的單詞 We 替換為單詞 SQL

SELECT
  REPLACE('We Will, We Will Rock You!', 'We', 'SQL') message;Code language: SQL (Structured Query Language) (sql)

試一試

輸出

           message
------------------------------
 SQL Will, SQL Will Rock You!

請注意,REPLACE 函式對子字串的搜尋是區分大小寫的。

例如,以下語句將單詞 We 替換為單詞 SQL。但是,它不會將單詞 we 替換為單詞 SQL

SELECT
  REPLACE('We will, we will rock you!', 'We', 'SQL') message;Code language: SQL (Structured Query Language) (sql)

試一試

輸出

           message
-----------------------------
 SQL will, we will rock you!

如果 REPLACE 函式沒有找到子字串,它將不執行任何操作並返回原始字串。

例如,以下語句返回原始字串,因為輸入字串不包含單詞 WE

SELECT
  REPLACE('We will, We will rock you!', 'WE', 'SQL') message;Code language: SQL (Structured Query Language) (sql)

輸出

          message
----------------------------
 We will, We will rock you!

將 SQL REPLACE 函式與 UPDATE 語句結合使用 #

我們將使用示例資料庫中的 employees 表。

SQL REPLACE Function - employees table

以下語句使用 REPLACE() 函式將電話號碼中的字元 . 替換為字元 -

SELECT
  first_name,
  last_name,
  REPLACE(phone_number, '.', '-') formatted_phone_number
FROM
  employees
ORDER BY
  first_name,
  last_name;Code language: SQL (Structured Query Language) (sql)

試一試

要將 employees 表的 phone_number 列中的字元 . 替換為字元 -,您可以使用 UPDATE 語句。

UPDATE employees
SET
  phone_number = REPLACE(phone_number, '.', '-');Code language: SQL (Structured Query Language) (sql)

試一試

以下 SELECT 語句從 employees 表中檢索資料以驗證更新。

SELECT
  first_name,
  last_name,
  phone_number
FROM
  employees
ORDER BY
  first_name,
  last_name;

輸出

 first_name  |  last_name  | phone_number
-------------+-------------+--------------
 Adam        | Fripp       | 650-123-2234
 Alexander   | Hunold      | 590-423-4567
 Alexander   | Khoo        | 515-127-4562
 Britney     | Everett     | 650-501-2876
 Bruce       | Ernst       | 590-423-4568
...

摘要 #

  • 使用 SQL REPLACE 函式將字串中所有出現的子字串替換為另一個子字串。

資料庫 #

本教程是否有幫助?
© .