PostgreSQL Oracle兼容性 - 計算字符長度與字節長度(char(?) 與varchar(?)空格如何計算長度)
標簽
PostgreSQL , Oracle , 字符長度 , 字節長度 , 空格 , varchar , char , 定長 , 變長 , 末尾追加空格
背景
由於多字節字符的存在,所以在數據庫應用中,通常會出現兩種計算字符串長度的需求:
1、計算字符串個數
2、計算字節數
在不同的數據庫中,使用的函數不一樣。
如何計算字符和字節個數
https://stackoverflow.com/questions/17062065/how-to-select-data-items-of-a-certain-length
Assuming you want the length in characters, the function names vary with RDBMS;
MySQL: CHAR_LENGTH().
Oracle: LENGTH().
SQL Server: LEN().
PostgreSQL: CHAR_LENGTH() or LENGTH().
SQLite: LENGTH().
If you want the length in bytes, it's instead;
MySQL: LENGTH().
Oracle: LENGTHB().
SQL Server: DATALENGTH().
PostgreSQL: OCTET_LENGTH().
For example, selecting all rows with names longer than 10 characters in MySQL would be;
SELECT * FROM myTable WHERE CHAR_LENGTH(name) > 10;
變長和定長的區別,字符計算個數的區別
以PostgreSQL為例。
1、定長,末尾自動追加空格,計算字符長度時,不計算末尾的空格。計算字節長度時,計算空格。
postgres=# select octet_length('abc '::char(1000));
octet_length
--------------
1000
(1 row)
postgres=# select char_length('abc '::char(1000));
char_length
-------------
3
(1 row)
postgres=# select char_length('你好abc '::char(1000));
char_length
-------------
5
(1 row)
postgres=# select octet_length('你好abc '::char(1000));
octet_length
--------------
1004
(1 row)
2、變長,末尾不追加空格,計算字符長度時,計算空格。計算字節長度時,計算空格。
postgres=# select char_length('abc '::varchar(1000));
char_length
-------------
7
(1 row)
postgres=# select octet_length('abc '::varchar(1000));
octet_length
--------------
7
(1 row)
postgres=# select octet_length('你好abc '::varchar(1000));
octet_length
--------------
13
(1 row)
postgres=# select char_length('你好abc '::varchar(1000));
char_length
-------------
9
(1 row)
最後更新:2017-11-12 01:34:47