digoal
2017-11-03
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)
您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。开不开森.