Home [SQL] 操作字串 (取得長度 Len、Datalenth)
Post
Cancel

[SQL] 操作字串 (取得長度 Len、Datalenth)

範例 Len()

顯示商品名稱與商品名稱的長度

1
2
--顯示商品名稱與商品名稱的長度
select 商品名稱, len(商品名稱) "商品名稱的長度" from 商品清單

執行結果:

1
2
3
4
5
6
7
8
9
10
11
商品名稱	商品名稱的長度
桌上型電腦	5
筆記型電腦	5
17吋螢幕	5
19吋螢幕	5
15吋液晶螢幕	7
數位相機	4
印表機	3
掃描器	3
HUB	3
網路卡	3

Len()、Datalenth()

  • Len():計算字串的個數。不分中英文,都會被算成 1byte
  • Datalenth():計算字串的 byte數,分中英文 (中文佔 2bytes 英文佔 1byte)

Len 尾端所有的空格都不算(前、中空格算,尾端空格不算,會排除尾端空格)
Datalenth 包括空格(前中後所有的空格都算,幾個空格就就個bytes)

len 會回傳己經刪除後方空白字串的字元數。在字串當中的空白字元雖然都會被當作是有效字元來計算,但尾端後面所有的空白字串都會被忽視。

Len()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
--Len
--英文(1byte)、中文(2bytes)都會被算成1個字元
select len('abc') --3
select len('您好') --2
select len('您好R') --3

--後加空白(會被trim掉尾端所有的空白)
select len('abc ') --3
select len('您好 ') --2

--前中加空白(會被當成有效字元)
select len(' a bc ') --5
select len(' 您 好 ') --4

--空字串
select len('') --0(空字串)

Datalength()

1
2
3
4
5
6
7
8
9
10
11
12
13
--Datalength
--要取得字串bytes數,要使用 datalenth()
select DATALENGTH('您好') --4
select DATALENGTH('abc') --3

--前中後加空白(都被當成有效字元)
select DATALENGTH(' 您 好 ') --7
select DATALENGTH(' a bc ') --6

--空字串、空白字串(幾個空格就就個bytes)
select DATALENGTH('') --0(空字串)
select DATALENGTH(' ') --1(1個空白字串)
select DATALENGTH('  ') --2(2個空白字串)

空字串、空格(空白字串)

  • Len 不管幾個空格,長度都是0
  • Datalength 有幾個空格就有幾 bytes 數
1
2
3
4
5
6
7
8
9
10
11
--空字串(沒有空格)
select len('') --0
select datalength('') --0

--1個空格
select len(' ') --0
select datalength(' ') --1

--2個空格
select len('  ') --0
select datalength('  ') --2

MSDN DATALENGTH datalength-transact-sql
MSDN LEN len-transact-sql
MSDN CHAR char-transact-sql

This post is licensed under CC BY 4.0 by the author.