Oracle中clob与varchar字段互转

1、clob字段转varchar字段主要用到dbms_lob.substr方法,该方法有三个参数,分别是截取的clob字段、截取长度以及起始位置,其中字段名为必须的,截取长度以及其实位置可以根据需要使用。

dbms_lob.substr(字段名,长度,起始位置)

2、varchar转clob使用to_clob()方法,其官方解释如下:

The TO_CLOB function converts NCLOB values in a LOB column or other character strings to CLOB values. char can be any of the datatypes CHAR, VARCHAR2, NCHAR,NVARCHAR2, CLOB, or NCLOB.

Oracle executes this function by converting the underlying LOB data from the national character set to the database character set.

to_clob(字段名)

下面举例进行说明(在语句执行后,请注意提交):

首先创建测试表,表中包含三个字典,标识码、clob测试字段和varchar测试字段。

create table t_test(id number,f_lob clob,f_str varchar(4000));

在表中插入一条测试数据,其中clob和varchar字段默认都为空。

insert into t_test(id ,f_lob ,f_str ) values (1,empty_clob(),'');

设置字符串为4000长度,内容随机

update t_test t set t.f_str=(SELECT DBMS_RANDOM.STRING ('x', 4000) FROM DUAL) where t.id=1;

设置clob字段的值为f_str字段的值

update t_test t set t.f_lob=to_clob(t.f_str) where t.id=1;

设置f_str的值为clob字段的值

update t_test t set t.f_str='' where t.id=1;
update t_test t set t.f_str=dbms_lob.substr(t.f_lob,4000,1) where t.id=1;

注意:因为clob的字段长度最大为4GB,varchar的最大长度为4000,所以在转换的时候可能会造成数据部分内容丢失,因此在转换之前,建议先通过DBMS_LOB.GETLENGTH(字段名)方法查看字段的长度后再进行转换,避免数据内容丢失。

posted on 2020-10-09 15:22  jingkunliu  阅读(11322)  评论(0编辑  收藏  举报

导航