摘要:在本教程中,您將學習如何使用 SQL RTRIM 函式來返回一個新字串,該字串移除了原字串末尾的指定字元。
SQL RTRIM 函式簡介 #
RTRIM 函式接收一個字串,並返回一個新字串,該新字串移除了輸入字串末尾的指定字元。
下面展示了 RTRIM 函式的語法:
RTRIM(string, [trim_characters])Code language: SQL (Structured Query Language) (sql)RTRIM 函式接受兩個引數:
string:您想要移除尾隨字元的輸入字串。trim_characters:(可選)一個您想從輸入字串中修剪的字元組成的字串。如果省略trim_characters,RTRIM函式將預設移除空格。
RTRIM 函式返回一個新字串,該字串移除了輸入字串末尾的所有 trim_characters。但是,它不會修改輸入字串本身。
在實踐中,您會發現 RTRIM 函式在清理字串時非常有用。
我們將使用HR 示例資料庫中的 employees 表來演示 RTRIM 函式。

移除尾隨空格 #
首先,向 employees 表中插入一個新行,其名字(first name)和姓氏(last name)都帶有一個尾隨空格。
INSERT INTO
employees (
employee_id,
first_name,
last_name,
email,
phone_number,
hire_date,
job_id,
salary,
manager_id,
department_id
)
VALUES
(
406,
'Jane ',
'Doe ',
'[email protected]',
'515.123.8191#',
'1994-06-07',
1,
9000.00,
205,
11
);Code language: SQL (Structured Query Language) (sql)其次,查詢 first_name 以空格結尾的員工。
SELECT
first_name,
RTRIM(first_name) AS trimmed_name
FROM
employees
WHERE
first_name LIKE '% ';Code language: SQL (Structured Query Language) (sql)輸出
first_name | trimmed_name
------------+--------------
Jane | JaneCode language: SQL (Structured Query Language) (sql)在這個查詢中:
第三,從 first_name 列中移除尾隨空格。
UPDATE employees
SET
first_name = RTRIM(first_name)
WHERE
first_name LIKE '% ';Code language: SQL (Structured Query Language) (sql)移除特定字元 #
以下查詢返回員工 ID 為 406 的員工的名字和電話號碼,並從 phone_number 中移除了尾隨字元 #。
SELECT
first_name,
phone_number,
RTRIM(phone_number, '#') AS plain_phone_number
FROM
employees
WHERE
employee_id = 406;Code language: SQL (Structured Query Language) (sql)輸出
first_name | phone_number | plain_phone_number
------------+---------------+--------------------
Jane | 515.123.8191# | 515.123.8191Code language: SQL (Structured Query Language) (sql)在這個例子中,我們使用 RTRIM 函式來修剪電話號碼末尾的字元 #。
您可以在 UPDATE 語句中使用 RTRIM 函式來移除電話號碼中的字元 #。
UPDATE employees
SET
phone_number = RTRIM(phone_number, '#')
WHERE
employee_id = 406;Code language: SQL (Structured Query Language) (sql)在條件邏輯中使用 RTRIM 函式 #
以下查詢使用 RTRIM 函式來標記那些姓氏包含尾隨空格的員工。
SELECT
employee_id,
last_name,
CASE
WHEN last_name != RTRIM(last_name) THEN 'Has trailing spaces'
ELSE 'No trailing spaces'
END AS status
FROM
employees
ORDER BY
last_name;Code language: SQL (Structured Query Language) (sql)摘要 #
- 使用
RTRIM函式可以返回一個新字串,該字串移除了輸入字串末尾的指定字元。 - 如果省略
trim_characters,RTRIM函式預設移除尾隨空格。
資料庫 #
本教程是否有幫助?