您的位置:首页 > 博客中心 > 数据库 >

ORACLE VARCHAR2最大长度问题

时间:2022-03-10 17:56

VARCHAR2数据类型的最大长度问题,是一个让人迷惑的问题,因为VARCHAR2既分PL/SQL Data Types中的变量类型,也分Oracle Database中的字段类型。简单的说,要看你在什么应用场景下,否则难以回答VARCHAR2数据类型的最大长度问题。

ORACLE数据库字段类型

关于Oracle Database中的字段的VARCHAR2类型的最大长度,我们先看下面的例子:

如上所示,在Oracle Database中,VARCHAR2字段类型,最大值为4000,SQL参考手册中也明确指出VARCHAR2的最大大小为4000,注意此处的最大长度是指字节长度,而不是指字符个数。这个跟参数NLS_LENGTH_SEMANTICS有一定关系,如下所示,当参数NLS_LENGTH_SEMANTICS为字节时,定义的变量长度为字节长度 

如下所示,本数据库NLS_CHARACTERSET值为AL32UTF8,一个汉字占三个字节

如果将参数NLS_LENGTH_SEMANTICS,则定义VARCHAR2(7)表示 

不管参数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 any multibyte 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个字符串。

热门排行

今日推荐

热门手游