【Oracle】 Oracle BLOB转CLOB出现字符乱码问题

【问题】BLOB类型转CLOB出现乱码问题

CREATE OR REPLACE FUNCTION BlobToClob(blob_in IN BLOB) RETURN CLOB AS
    v_clob    CLOB;
    v_varchar VARCHAR2(4000);
    v_start   PLS_INTEGER := 1;
    v_buffer  PLS_INTEGER := 4000;
BEGIN
    DBMS_LOB.CREATETEMPORARY(v_clob, TRUE);
    FOR i IN 1 .. CEIL(DBMS_LOB.GETLENGTH(blob_in) / v_buffer) LOOP
        v_varchar := UTL_RAW.CAST_TO_VARCHAR2( DBMS_LOB.SUBSTR(blob_in,
                                                              v_buffer,
                                                              v_start)
                                                             
                                                              );
        DBMS_LOB.WRITEAPPEND(v_clob, LENGTH(v_varchar),  v_varchar );
        v_start := v_start + v_buffer;
    END LOOP;
    RETURN v_clob;
END BlobToClob;

中文出现乱码


【分析】字符应该需要转换

百度后

select convert(UTL_RAW.CAST_TO_VARCHAR2(blob_field), 'zhs16gbk', 'AL32UTF8') from test_blob;

select UTL_RAW.CAST_TO_VARCHAR2(UTL_RAW.CONVERT(blob_field, 'AMERICAN_AMERICA.zhs16gbk', 'AMERICAN_AMERICA.AL32UTF8'

blob转字符串是用了UTL_RAW.CAST_TO_VARCHAR2()函数,
转码可以用CONVERT()和UTL_RAW.CONVERT()两个函数,CONVERT()函数相比之下就不需要加英文字符集了
3个参数,utl_raw.convert(a,b,c),b为当前数据库可识别的字符集,可以从nls_database_parameters中查看,c为当前2进制数据存储使用的字符集。该函数将a从字符集c转换到字符集b。字符集参数要写全,比如'AMERICAN_AMERICA.US7ASCII','.'前面为英文字符集,后面为中文字符集。

【结论】


CREATE OR REPLACE FUNCTION BlobToClob(blob_in IN BLOB) RETURN CLOB AS
    v_clob    CLOB;
    v_varchar VARCHAR2(4000);
    v_start   PLS_INTEGER := 1;
    v_buffer  PLS_INTEGER := 4000;
BEGIN
    DBMS_LOB.CREATETEMPORARY(v_clob, TRUE);
    FOR i IN 1 .. CEIL(DBMS_LOB.GETLENGTH(blob_in) / v_buffer) LOOP
        v_varchar := UTL_RAW.CAST_TO_VARCHAR2( convert(DBMS_LOB.SUBSTR(blob_in,
                                                              v_buffer,
                                                              v_start),
                                                              'ZHS16GBK', 'UTF8'
                                                              ));
        DBMS_LOB.WRITEAPPEND(v_clob, LENGTH(v_varchar),  v_varchar );
        v_start := v_start + v_buffer;
    END LOOP;
    RETURN v_clob;
END BlobToClob;



你可能感兴趣的:(SQL)