Convert XMLTYPE to VARCHAR2 or CLOB?
Does anyone know how to convert an XMLTYPE variable to VARCHAR2 or CLOB? I am using the XMLELEMENT function to select XML into an XMLTYPE variable (VARCHAR2 and CLOB will not accept xml from this function). But I would like to convert the xml in the XMLTYPE variable to VARCHAR2 or CLOB. Can anyone please tell me how to do this? The reason is that I would like to call this procedure from MS ADO.
Anthony Sneed
email: [email protected]
Hi,
But I would like to convert the xml in the XMLTYPE variable to VARCHAR2 or CLOB.You can select XMLType data using PL/SQL or Java. You can also use the getClobVal(), getStringVal(), or getNumberVal() functions to retrieve XML as a CLOB, VARCHAR, or NUMBER, respectively.
Example 4-18 Selecting XMLType Columns using getClobVal()
This example shows how to select an XMLType column using SQL*Plus:
SET long 2000
SELECT e.poDoc.getClobval() AS poXML
FROM po_xml_tab e;
POXML
<?xml version="1.0"?>
<PO pono="2">
<PNAME>Po_2</PNAME>
<CUSTNAME>Nance</CUSTNAME>
<SHIPADDR>
<STREET>2 Avocet Drive</STREET>
<CITY>Redwood Shores</CITY>
<STATE>CA</STATE>
</SHIPADDR>
</PO>
Look into the documentation: Oracle9i XML Database Developer's Guide - Oracle XML DB for more details.
Hope that helps.
OTN team@IDC
Similar Messages
-
How to convert XMLTYPE data into CLOB without using getclobval()
Please tell me how to convert data which is stored in the table in XMLTYPE column to a CLOB.
When i use getClobVal(), i get an error. So please tell me some other option except getClobVal()CREATE OR REPLACE PACKAGE BODY CONVERT_XML_TO_HTML AS
FUNCTION GENERATE_HTML(TABLE_NAME VARCHAR2, FILE_NAME VARCHAR2, STYLESHEET_QUERY VARCHAR2, WHERE_CLAUSE VARCHAR2, ORDERBY_CLAUSE VARCHAR2) RETURN CLOB IS
lHTMLOutput XMLType;
lXSL CLOB;
lXMLData XMLType;
FILEID UTL_FILE.FILE_TYPE;
HTML_RESULT CLOB;
SQL_QUERY VARCHAR2(300);
WHERE_QUERY VARCHAR2(200);
fileDirectory VARCHAR2(100);
slashPosition NUMBER;
actual_fileName VARCHAR2(100);
XML_HTML_REF_CUR_PT XML_HTML_REF_CUR;
BEGIN
IF WHERE_CLAUSE IS NOT NULL AND ORDERBY_CLAUSE IS NOT NULL THEN
SQL_QUERY := 'SELECT * FROM ' || TABLE_NAME ||' WHERE ' || WHERE_CLAUSE || ' ORDER BY ' || ORDERBY_CLAUSE;
ELSE IF WHERE_CLAUSE IS NOT NULL AND ORDERBY_CLAUSE IS NULL THEN
SQL_QUERY := 'SELECT * FROM ' || TABLE_NAME || ' WHERE ' || WHERE_CLAUSE;
ELSE IF WHERE_CLAUSE IS NULL AND ORDERBY_CLAUSE IS NOT NULL THEN
SQL_QUERY := 'SELECT * FROM ' || TABLE_NAME || ' ORDER BY ' || ORDERBY_CLAUSE;
ELSE IF WHERE_CLAUSE IS NULL AND ORDERBY_CLAUSE IS NULL THEN
SQL_QUERY := 'SELECT * FROM ' || TABLE_NAME;
END IF;
END IF;
END IF;
END IF;
OPEN XML_HTML_REF_CUR_PT FOR SQL_QUERY;
lXMLData := GENERATE_XML(XML_HTML_REF_CUR_PT);
--lXSL := GET_STYLESHEET(STYLESHEET_QUERY);
if(lXMLData is not null) then
dbms_output.put_line('lXMLData pass');
else
dbms_output.put_line('lXMLData fail');
end if;
lHTMLOutput := lXMLData.transform(XMLType(STYLESHEET_QUERY));
--INSERT INTO TEMP_CLOB_TAB2 VALUES(CLOB(lHTMLOutput));
if(lHTMLOutput is not null) then
dbms_output.put_line('lHTMLOutput pass');
else
dbms_output.put_line('lHTMLOutput fail');
end if;
HTML_RESULT := lHTMLOutput.getclobVal();
if(HTML_RESULT is not null) then
dbms_output.put_line('HTML_RESULT pass'||HTML_RESULT);
else
dbms_output.put_line('HTML_RESULT fail');
end if;
-- If the filename has been supplied ...
IF FILE_NAME IS NOT NULL THEN
-- locate the final '/' or '\' in the pathname ...
slashPosition := INSTR(FILE_NAME, '/', -1 );
IF slashPosition = 0 THEN
slashPosition := INSTR(FILE_NAME,'\', -1 );
END IF;
-- separate the filename from the directory name ...
fileDirectory := SUBSTR(FILE_NAME, 1,slashPosition - 1 );
actual_fileName := SUBSTR(FILE_NAME, slashPosition + 1 );
END IF;
DBMS_OUTPUT.PUT_LINE(fileDirectory||' ' ||actual_fileName);
FILEID := UTL_FILE.FOPEN(fileDirectory,actual_fileName, 'W');
UTL_FILE.PUT_LINE(FILEID, '<title> hi </title>');
UTL_FILE.PUT_LINE(FILEID, HTML_RESULT);
UTL_FILE.FCLOSE (FILEID);
DBMS_OUTPUT.PUT_LINE('CLOB SIZE'||DBMS_LOB.GETLENGTH(HTML_RESULT));
RETURN HTML_RESULT;
--RETURN lHTMLOutput;
EXCEPTION
WHEN OTHERS
THEN DBMS_OUTPUT.PUT_LINE('ERROR!!!!!!!!!!!!');
END GENERATE_HTML;
FUNCTION GENERATE_XML(XML_HTML_REF_CUR_PT XML_HTML_REF_CUR) RETURN XMLType IS
qryCtx DBMS_XMLGEN.ctxHandle;
result CLOB;
result1 xmltype;
BEGIN
qryCtx := DBMS_XMLGEN.newContext(XML_HTML_REF_CUR_PT);
result := DBMS_XMLGEN.getXML(qryCtx);
--dbms_output.put_line(result);
result1 := xmltype(result);
INSERT INTO temp_clob VALUES(result);
if(result1 is not null) then
dbms_output.put_line('pass');
else
dbms_output.put_line('fail');
end if;
return result1;
DBMS_XMLGEN.closeContext(qryCtx);
END GENERATE_XML;
END CONVERT_XML_TO_HTML;
This is the code which i am using to generate the XML and subsequently to generate the HTML output out of that using a XSL stylesheet.
The error is Numeric or value error.. -
Change Parameter from VarChar2 to CLOB
Hi,
I have a function csvToArray which takes a csv string and converts it to an array.
PROCEDURE csvToArray(p_csvString IN VarChar2,
p_count OUT PLS_INTEGER,
p_array OUT ARRAY_T) IS...
Unfortunately the size of the csvString being passed in exceeds 32K, so I was thinking about changing the type of the csvString from Varchar2 to CLOB,i.e
PROCEDURE csvToArray(p_csvString IN CLOB,
p_count OUT PLS_INTEGER,
p_array OUT ARRAY_T) IS...
The procedure only uses the string functions instr and substr to find the elements of the csv string to place in an array.
I've tested the change and it works, but is there anything I should consider with the change to the data type, or will the above always work fine? The extreme max size of p_csvString would be around 150K.
Database version is 10.2.0.4.0
ThanksHi,
This test maybe helpful
Passed Length 65K test
create or replace procedure my_pro ( pclob clob)
is
begin
dbms_output.put_line('clob passed LEN:' ||
dbms_lob.getlength(pclob) );
end;
Procedure created.
SQL> exec my_pro( to_clob(lpad('x',32767,'c')||lpad('x',32767,'c')||'x'));
clob passed LEN:65535
PL/SQL procedure successfully completed.SS -
Can I convert existing column BLOB to CLOB?
Hi ,
I need conversion of existing column from BLOB to CLOB. Kindly sueggest workaround. Table structure is as
{ desc tab1;
Name Null? Type
Name Null? Type
RECID NOT NULL VARCHAR2(255)
XMLRECORD BLOB}
I need to convert it from blob to clob. Kindly provide workaround.
RegardsHi,
How can i use this function for my scenario
1. Table name is "test" and XMLRECORD column should be in CLOB without drop table. Kindly update this fuction as per my scenario and also provide all the steps
CREATE OR REPLACE FUNCTION blob_to_clob (blob_in IN BLOB)
RETURN CLOB
AS
v_clob CLOB;
v_varchar VARCHAR2(32767);
v_start PLS_INTEGER := 1;
v_buffer PLS_INTEGER := 32767;
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 blob_to_clob;
] -
Hi there,
I am looking for a convertion, long to varchar2, in a sql statement.
If I run the following query :
select data_default from user_tab_columns
It works fine in sql developper but when I execute it in my PHP code it returns:
Notice: Undefined index: DATA_DEFAULT in /opt/lampp/htdocs/datamodel/index.php on line 64
This issue is due in the case where the columns has null.
So I try with the NVL function:
select nvl(data_default, 'null') from user_tab_columns
ORA-00932: inconsistent datatypes: expected LONG got CHAR
I found on internet some people are using the substr function but it did not working for me.
select substr(data_default, 1, 2000) from user_tab_columns
ORA-00932: inconsistent datatypes: expected NUMBER got LONG
Any one has an idea ?
Regards !See this thread as well you can get an exaple user function
ORA-00932: inconsistent datatypes
G. -
How do I convert ClobDomain to java.sql.Clob?
I have an instance of oracle.jbo.domain.ClobDomain and i need
to convert it to oracle.sql.CLOB. How do I do this?Sascha, I tried your solution:
clobData = (CLOB) content.getData();
Alas, it does not work. Although content has a value, clobData becomes null
Also, if I take a look in the source ClobDomain.data, the method getData has the following
comment:
* Internal:Applications should not use this method.
Does anybody know a way out?
lebbol -
Converting in varchar2 to clob in select query
Hi All,
Help me in displaying vachar2 data and clob data one below the other. Following steps i had taken but failed to achieve any results on ora9.2.0.1.0.
create table temp_ajay
ename varchar2(20)
create table temp_ajayx
ename clob
select to_clob(ename) from temp_ajay
union
select ename from temp_ajayx
above gave
select to_clob(ename) from temp_ajay * ERROR At line 1: Ora-00932: incoherent types of data: - waited; CLOB obtained
as error.
How do i resolve this? Pls help
rgds,
Ajayselect to_nchar(ename) from temp_ajay
union
select to_nchar(ename) from temp_ajayx;
or
select to_char(ename) from temp_ajay
union
select to_char(ename) from temp_ajayx;Message was edited by:
Jameel -
Hi people,
I'm using DBD::Oracle perl module to access data in Oracle Database. the database characterset is WE8MSWIN1252 and my data are utf8 encoded in an xmltype.
I can get the xml using this query :
select x.xmlbody.getCLOBVal() FROM tableA x;
However with this query the xmlbody is WE8MSWIN1252 encoded cause I get a CLOB.
How can get an utf8 encoded value with this query in sqlplus :
select xmlbody from tableA;
But I can use this query in my perl script cause the xmltype is not supported in the last version of the module DBD::Oracle. How to get a varchar2 value from this query ? How can I cast this object type ?
thanksNote I would STRONGLY recommend converting the database characater set to AL32UTF8 if at all possible.... Bad things will happen if you end up with an UTF8 characater that cannot be represented in the database characater set.
-
How to create index on a xmltype column stored as CLOB
actually i have two problems.
i uploaded this schemaA.xsd file into xmldb repository without problems. registration also went ok.
BEGIN
DBMS_XMLSCHEMA.registerSchema(
schemaURL => 'http://xmlns.example.com/xdb/documentation/schemaA.xsd'
,schemaDoc => sys.UriFactory.getUri('/home/dev/schemaA.xsd')
,local => TRUE
,genBean => false
,genTypes => TRUE
,genTables => false
,enableHierarchy => DBMS_XMLSCHEMA.ENABLE_HIERARCHY_NONE
END;
then i run this:
create table pf_table_a(
id VARCHAR2(100) primary key,
xsd VARCHAR2(3000),
xml_document XMLType
) XMLTYPE COLUMN xml_document
STORE AS CLOB
XMLSCHEMA "http://xmlns.example.com/xdb/documentation/schemaA.xsd"
ELEMENT "order";
and got this error:
SQL> @d:\usr\dev\perftest\create_tables.sql
Table created.
create table pf_table_a(
ERROR at line 1:
ORA-00955: name is already used by an existing object
anyway the table was created. so i went on to create indexes.
SQL> create index pf_a_index on pf_table_a(extractValue(OBJECT_VALUE, '/order@or
derNo'));
create index pf_a_index on pf_table_a(extractValue(OBJECT_VALUE, '/order@orderNo
ERROR at line 1:
ORA-04063: table "BAUSER1.PF_TABLE_A" has errors
this of course is wrong. because the command is for creating index of a XMLTYPE table. no a column. but what is the correct command? thanks.
jack.actually i have two problems.
i uploaded this schemaA.xsd file into xmldb repository without problems. registration also went ok.
BEGIN
DBMS_XMLSCHEMA.registerSchema(
schemaURL => 'http://xmlns.example.com/xdb/documentation/schemaA.xsd'
,schemaDoc => sys.UriFactory.getUri('/home/dev/schemaA.xsd')
,local => TRUE
,genBean => false
,genTypes => TRUE
,genTables => false
,enableHierarchy => DBMS_XMLSCHEMA.ENABLE_HIERARCHY_NONE
END;
then i run this:
create table pf_table_a(
id VARCHAR2(100) primary key,
xsd VARCHAR2(3000),
xml_document XMLType
) XMLTYPE COLUMN xml_document
STORE AS CLOB
XMLSCHEMA "http://xmlns.example.com/xdb/documentation/schemaA.xsd"
ELEMENT "order";
and got this error:
SQL> @d:\usr\dev\perftest\create_tables.sql
Table created.
create table pf_table_a(
ERROR at line 1:
ORA-00955: name is already used by an existing object
anyway the table was created. so i went on to create indexes.
SQL> create index pf_a_index on pf_table_a(extractValue(OBJECT_VALUE, '/order@or
derNo'));
create index pf_a_index on pf_table_a(extractValue(OBJECT_VALUE, '/order@orderNo
ERROR at line 1:
ORA-04063: table "BAUSER1.PF_TABLE_A" has errors
this of course is wrong. because the command is for creating index of a XMLTYPE table. no a column. but what is the correct command? thanks.
jack. -
Hi,
I want to convert my Varchar2 vairable to CLOB to store in my database is that any way to do so ?
I have seen DBMS_LOB package but I dont understand how to use that . The DBMS_LOB package converts BFILE data to CLOB, so If any one knows how I can write intoa BFILE and then I can convert it to CLOB.
Regards,
Nishith PancholiHi!
Here's a quick example for you:
create table tmpl (f1 number, f2 clob);
declare
l_clob clob;
l_str varchar2(32767) := 'asdf';
begin
insert into tmpl values (1, l_str);
end;
select * from tmpl;
drop table tmpl;
Regards,
Andrew Velitchko
BrainBench MVP for Developer/2000
http://www.brainbench.com -
PL/SQL Solution for Converting Long to VarChar2
I recently had to convert a bunch of text stored in Long fields to a new VarChar2(2000) field in the same table.
As you know if you've ever tried, you can't use a basic SQL the update statement will not do this, e.g. update table1 set field2 = field1 (where field2 is VarChar(2000) and field1 is Long) fails as does update table1 set field2 = substr(field1, 1, 2000).
Interestingly PL/SQL's implementation of SubStr does work with Long fields. I was able to put together the following anonymous PL./SQL block to accomplish the task (msgtext is varchar(2000), msgtext2 is Long):
DECLARE
CURSOR message_cur
IS
SELECT ROWID, msgtext, msgtext2
FROM tlrcmmessages
FOR UPDATE;
message_rec message_cur%ROWTYPE;
BEGIN
OPEN message_cur;
LOOP
FETCH message_cur
INTO message_rec;
EXIT WHEN message_cur%NOTFOUND;
UPDATE tlrcmmessages
SET msgtext = SUBSTR(message_rec.msgtext2, 1, 2000)
WHERE CURRENT OF message_cur;
END LOOP;
CLOSE message_cur;
END;
I hopes this helps others out there in similar circumstances.
Good luck,
Rob Bratton, Bratton EnterprisesOracle strongly recommends to convert LONG fields into CLOB:
http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96590/adfnstyp.htm#429091
Rgds. -
Varchar2 to CLOB : Best Options to do it ?
Helllo,
I have a table whcih is 20GB in size and has a Column which is a Varchar2 column.As varchar2 could store upto 4000 bytes of data,we have a requiremnet where the column can have more than 4000 bytes of data and we decided to convert it to a CLOB column.
What are the best and fastest way of doing this?
OPTION 1_
1. First create the temporary table
CREATE TABLE P_C_V_NEW
(TESTID_NUM NUMBER,
DATAPOINT NUMBER,
DATAPOINT_DATE DATE ,
CHANGE_FLAG VARCHAR2(1),
CHANNEL_VALUES CLOB )
2. Insert the data from original to the temporaray table
INSERT INTO P_C_V_NEW (SELECT TESTID_NUM,DATAPOINT, DATAPOINT_DATE, CHANGE_FLAG,CHANNEL_VALUES FROM P_C_V)
3.Rename the temporary table to Original table
RENAME P_C_V_NEW TO PAM_CHANNEL_VALUES
OPTION 2:_
SQL> alter table P_C_V add (NEW_CHANNEL_VALUE clob);
Table altered.
SQL> update P_C_V set NEW_CHANNEL_VALUE = CHANNEL_VALUE;
1 row updated.
SQL> alter table PP_C_V drop column CHANNEL_VALUE;
Table altered.
SQL> alter table P_C_V rename column NEW_CHANNEL_VALUE to CHANNEL_VALUE;
Table altered.
SQL> desc pam_channel_values
Name Null? Type
TESTID_NUM NUMBER
DATAPOINT NOT NULL NUMBER
DATAPOINT_DATE NOT NULL DATE
CHANGE_FLAG NOT NULL CHAR(1)
CHANNEL_VALUES CLOB
OPTION 3
Use DBMS_REDEFINITION ?
This original table contains 11714457 records.
Thanks
GAGI would prefer somthing as like method1 as
Create table x as select * from old table.
beacuse it would be the fastest way to load the data compare to update of method 2.
Only issue is that the in table x the new constriant and index need to be created if they are presenti on old .
and even if you want to go with method 2 you need to do the update in BULK collect way in plsql
not simple sql like this beacuse you need a big amount of rollback segment spac
update P_C_V set NEW_CHANNEL_VALUE = CHANNEL_VALUE;Cheers
Nawneet -
The most effective way from varchar2 to CLOB?
this is my table's TAB structure on Oracle 10g r2:
TAB_ID (PK),
TAB2_ID (FK constraint to TAB2(TAB2_ID), index created),
TEXT varchar2(4000)
What is the most effective way to convert varchar2(4000) column to CLOB column?
1. create new table TAB_NEW with column TEXT as CLOB,
then insert /*+ APPEND */ into TAB_NEW SELECT * FROM TAB,
then rename table TAB to TAB_OLD,
then drop constraint and indexes
then rename TAB_new to TAB
then add constraints primary key and foreign key,
then add index on TAB2_ID
then drop table TAB_OLD
OR
2. rename column TEXT(varchar2) to TEXT_OLD
then add column TEXT(type CLOB)
then update(how the most effective?) TAB set TEXT=TEXT_OLD
drop column TEXT_OLD.1 will work, as you can assign a VARCHAR2 to a CLOB and Oracle will convert it.
2 is redundant.
Sybrand Bakker
Senior Oracle DBA -
Question in ER_DESIGN with VARCHAR2 and CLOB
hi experts,
i want to know in your design experience, how do you manage thus situation:
a text field, which must have features of full-text search for all the text, normally, it should be less than 4000 character long, (it means we can use varchar2 field for it),
however, sometimes it should longer than 4000 characters.
i think, i could have two options,
the first, i cut it into peices with no one can be longer than 4000, nevertheless, this method will face difficult to provide full-text search.
the other is to build a new table with clob field, the original table will involve a field of varchar2, the other field of number will be a reference guild the the clob table.
if the record's text long do not over 4000, it will record in the field of varchar2 as usual, once it is longer than 4000, it will be stored in the clob field in other table.i can get it with the guild field(index).
so i can provide full-text search functions for this type of record, and much storage space can be saved.
However, i do not know whether i am doing on a right way or in a foolish way, may be some other wise method can do simply . that what i want to question on you.
thank you very much.
frederickNo, I don't have tables of values. I have a java 1.5 enumeration, like for instance:
public enum VelocityConvention {
RELATIVISTIC,
REDSHIFT;
}and a class Velocity that contains a convention and a value like so:
public class Velocity {
public VelocityConvention getConvention() {...}
public double getValue() {...}
public void set(VelocityConvention conv, double value) {...}
}When I persist the Velocity class to the database, I want a field called convention that holds the appropriate value of the enumeration. That much is done how I explained before.
I want to have a selectOneMenu for setting the convention. Via trial and error, I found that MyFaces wasn't able to automatically convert from a string back to a proper VelocityConvention enum constant. It can, of course, convert from the enum to a string because it just calls toString(). But I need both directions for any UIInput element I use, be it a selectOne, or just a straight inputText. -
Convert result of query to CLOB
Hi,
I have a query which is 'execute immediate vc_query into vcl_result'. Here vc_query is a varchar2 which is holding my query and return some value, And vc_result is a CLOB.
Now, this statement is failing to execute and saying inconsistent datatypes.
Is there a way I can convert the result of the sql query in the variable to convert to clob?
Thanks,Yes and no. It depends.
a) why are you using execute immediate to execute a query?
b) why do you want the results stored in a CLOB?
c) what structure should the results have in the CLOB?
d) read the FAQ: Re: 2. How do I ask a question on the forums? and post sufficient details so people can answer you properly.
Maybe you are looking for
-
Opening Balances and Closing Balance of customer
Hi, Does SAP provide any standard customer account statement for Opening Balances and Closing Balance for specific date range have given in selection screen? The statement also contains reference number, order, and Delivery number. Note: FBL5N Transa
-
Measure Values are not shown in the pivot tables
Measures without aggregation (in rpd) are not shown in pivot table. Im trying to add multiple columns in the fact table as measures,one which is summable had has the SUM function and three which are not summable. The initial report will be as follows
-
Hello, I use RedHat 5.2 and I try to install Oracle 8 on may system. When I excute orainst, I have the following errors. ======================================== [root@linux-02 orainst]# . ./orainst : not a legal variable name : not a legal variable
-
Thunderbird not communicating with servers?
I'm using Thunderbird 24.6.0 on a Sony Vaio running Windows 7. Everything has been running along smoothly until about a week ago. One night I used Thunderbird to check my Comcast email (as I've done for years and years) and everything was normal. The
-
AS3, Flash movies and buttons
Okay, it's been a while since I used Flash (V.4) and things have moved on just a smidge since. In previous versions Flash was intuitive... coding was fairly minimal and doing the basics was straight forward. I need to use Flash to do some fairly simp