暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle char 类型字段修改为varchar2

原创 泡泡龙 2021-12-31
4650

   char的长度是固定的,而VARCHAR2的长度是可以变化的.

 比如,存储字符串“abc",对于CHAR (20),表示你存储的字符将占20个字节(包括17个空字符),

而同样的VARCHAR2 (20)则只占用3个字节的长度,20只是最大值,当你存储的字符小于20时,按实际长度存储。

 char转化成varchar2会在字符串后补充空格 . 所以如果将char类型修改为varchar2类型需要使用RTRIM函数删除字段末尾补充的空格。


以下引用 自 MOS: 


SOLUTION

EXAMPLE:

Note that the job column is currently a char column with a length of 11.

SQL> desc empcon
 Name                                      Null?    Type
 ----------------------------------------- -------- --------------------------

 EMPNO                                              NUMBER(4)
 ENAME                                              VARCHAR2(10)
 JOB                                                CHAR(11 CHAR)
 MGR                                                NUMBER(4)
 HIREDATE                                           DATE
 SAL                                                NUMBER(7,2)
 COMM                                               NUMBER(7,2)
 DEPTNO                                             NUMBER(2)

SQL> alter table empcon modify job varchar2 (11); 

(This alters the column to varchar2 but the length must be the same as the char column.)

Table altered.

SQL> desc empcon
 Name                                      Null?    Type
 ----------------------------------------- -------- --------------------------

 EMPNO                                              NUMBER(4)
 ENAME                                              VARCHAR2(10)
 JOB                                                VARCHAR2(11)
 MGR                                                NUMBER(4)
 HIREDATE                                           DATE
 SAL                                                NUMBER(7,2)
 COMM                                               NUMBER(7,2)
 DEPTNO                                             NUMBER(2)


SQL> update empcon e
  2  set e.job = RTRIM(e.job);

(This removes the blanks used to pad the char column)

 14 rows updated.


SOLUTION

=======================
To implement the solution, please execute the following steps:

1. Modify the column to be a varchar2.
2. Use the update statement with the rtrim function to remove the blanks on the varchar2 column.

Please note that trying to insert into a varchar2 column of lesser length than the char will result in the following error:

ORA-12899: value too large for column "SCOTT"."EMPCON"."JOB" (actual: 11, maximum: 9)






「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论