VARCHAR2数据类型的最大长度问题,是一个让人迷惑的问题,因为VARCHAR2既分PL/sql Data Types中的变量类型,也分Oracle Database中的字段类型。简单的说,要看你在什么应用场景下,否则难以回答VARCHAR2数据类型的最大长度问题。
ORACLE数据库字段类型
关于Oracle Database中的字段的VARCHAR2类型的最大长度,我们先看下面的例子:
sql> create table test ( name varchar2(4001) );
table test ( name varchar2(4001) )
*
ERROR at line 1:
ORA-00910: specified length too long for its datatype
table test ( name varchar2(4000) );
Table created.
如上所示,在Oracle Database中,VARCHAR2字段类型,最大值为4000,sql参考手册中也明确指出VARCHAR2的最大大小为4000,注意此处的最大长度是指字节长度,而不是指字符个数。这个跟参数NLS_LENGTH_SEMANTICS有一定关系,如下所示,当参数NLS_LENGTH_SEMANTICS为字节时,定义的变量长度为字节长度
如下所示,本数据库NLS_CHARACTERSET值为AL32UTF8,一个汉字占三个字节
ALTER SESSION SET NLS_LENGTH_SEMANTICS=BYTE;
Session altered
DROP TABLE TEST PURGE;
Table dropped
CREATE TABLE TEST ( NAME VARCHAR2(7));
Table created
sql> INSERT INTO TEST VALUES ('字');
1 row inserted
COMMIT;
Commit complete
VALUES('字字字');
INSERT '字字字')
ORA-12899: value too large for column "SYSTEM"."TEST"."NAME" (actual: 9,maximum: 7)
SELECT LENGTH(NAME),LENGTHB(NAME) FROM TEST;
LENGTH(NAME) LENGTHB(NAME)
------------ -------------
1 3
如果将参数NLS_LENGTH_SEMANTICS,则定义VARCHAR2(7)表示
TABLE TEST;
1 3
3 9
不管参数NLS_LENGTH_SEMANTICS取值为字符或字节,其所能容纳的字符串的字节数都不能超过4000.
PL/sql变量类型:
接下来我们看看PL/sql中VARCHAR2变量类型,如下官方文档所示,它的最大字节长度为32767,所能容纳的字符个数取决于字符集。
Declaring Variables for Multibyte Characters
The maximum size of a CHAR or VARCHAR2 variable is 32,767 bytes,whether you specify the maximum size in characters or bytes. The maximum number of characters in the variable depends on the character set type and sometimes on the characters themselves:
Character Set Type |
Maximum Number of Characters |
Single-byte character set |
32,767 |
n-byte fixed-width multibyte character set (for example,AL16UTF16) |
FLOOR(32,767/n) |
n-byte variable-width multibyte character set with character widths between 1 and n bytes (for example,JA16SJIS or AL32UTF8) |
Depends on characters themselves—can be anything from 32,767 (for a string containing only 1-byte characters) through FLOOR(32,767/n) (for a string containing only n-byte characters). |
When declaring a CHAR or VARCHAR2 variable,to ensure that it can always hold n characters in anymultibyte character set,declare its length in characters—that is,CHAR(n CHAR) or VARCHAR2(n CHAR),where n does not exceed FLOOR(32767/4) = 8191.
可以通过下面一个PL/sql代码来验证一下,如下所示,可以定义一个VARCHAR2类型的变量,给其赋值6000个字符串。
V_OUT VARCHAR2(32767);
BEGIN
V_OUT := RPAD('T',6000,'M');
DBMS_OUTPUT.PUT_LINE(LENGTH(V_OUT));
END;
如果给VARCHAR2类型变量赋值超过23767,就会报@H_492_301@PLS-00215: String length constraints must be in range (1 .. 32767)错误。