字串轉換函式

SQL Server 的資料操作函式

Ana Voicu

Data Engineer

LOWER() 與 UPPER()

LOWER(character_expression)

  • 將字串全部轉為小寫。

UPPER(character_expression)

  • 將字串全部轉為大寫。
SQL Server 的資料操作函式

LOWER() 與 UPPER() 範例

SELECT 
    country,
    LOWER(country) AS country_lowercase,
    UPPER(country) AS country_uppercase
FROM voters;
| country | country_lowercase | country_uppercase |
|---------|-------------------|-------------------|
| Denmark | denmark           | DENMARK           |
| France  | france            | FRANCE            |
| Belgium | belgium           | BELGIUM           |
SQL Server 的資料操作函式

LEFT() 與 RIGHT()

LEFT(character_expression, number_of_characters)

  • 從字串開頭擷取指定字元數。

RIGHT(character_expression, number_of_characters)

  • 從字串結尾擷取指定字元數。
SQL Server 的資料操作函式

LEFT() 與 RIGHT() 範例

SELECT 
    country,
    LEFT(country, 3) AS country_prefix,
    email,
    RIGHT(email, 4) AS email_domain
FROM voters;
| country | country_prefix | email              | email_domain |
|---------|----------------|--------------------|--------------|
| Denmark | Den            | [email protected]   | .com         |
| France  | Fra            | [email protected]     | .com         |
| Belgium | Bel            | [email protected] | .com         |
SQL Server 的資料操作函式

LTRIM()、RTRIM() 與 TRIM()

LTRIM(character_expression)

  • 移除前導空白後回傳字串。

RTRIM(character_expression)

  • 移除尾端空白後回傳字串。

TRIM([characters FROM] character_expression)

  • 移除空白或指定字元後回傳字串。
SQL Server 的資料操作函式

REPLACE()

REPLACE(character_expression, searched_expression, replacement_expression)

  • 將字串中所有出現的指定片段替換為另一片段後回傳。
SELECT REPLACE('I like apples, apples are good.', 'apple', 'orange') AS result;
| result                          | 
|---------------------------------|
|I like oranges, oranges are good.|
SQL Server 的資料操作函式

SUBSTRING()

SUBSTRING(character_expression, start, number_of_characters)

  • 回傳字串的一部分。
SELECT SUBSTRING('123456789', 5, 3) AS result;
| result | 
|--------|
| 567    |
SQL Server 的資料操作函式

一起來練習吧!

SQL Server 的資料操作函式

Preparing Video For Download...