Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB2 cast a large CLOB (> 32KB) into text?

Tags:

varchar

db2

clob

I have a DB2 (9.5.1) table which is defined as follows:

CREATE TABLE MY_TABLE 
( 
   ID INTEGER DEFAULT 0 NOT NULL, 
   TEXT CLOB(104857600), 
   PRIMARY KEY (ID) 
);

Now if I want to query the actual text string that is stored in the CLOB I do it this way:

select cast(t.TEXT as varchar(32000))
  from MY_TABLE t
  where t.ID = 1;

The problem is now that my text gets truncated, but for a varchar the maximum length is 32KB, so this query fails:

select cast(t.TEXT as varchar(33000))
  from MY_TABLE t
 where t.ID = 1;

Is there another possibility how I can retrieve the full contents of a CLOB as text output?

Peter

like image 526
Peter Meier Avatar asked Apr 30 '12 11:04

Peter Meier


People also ask

What is CLOB data type in DB2?

A CLOB (character large object) value can be up to 2,147,483,647 characters long. A CLOB is used to store unicode character-based data, such as large documents in any character set.

Can we use CLOB instead of VARCHAR2 in Oracle?

1) if you are storing 4000 bytes or less in the database, use VARCHAR2 otherwise use CLOB. 2) if you are storing 32k bytes or less in PLSQL use VARCHAR2 otherwise use CLOB.


3 Answers

I found this elsewhere on the web and thought I would share seeing as it works around the 32k limit.

SELECT 
  XMLCAST (
    XMLPARSE (
      DOCUMENT CAST (
        MY_CLOB_DATA AS BLOB
      ) 
      PRESERVE WHITESPACE
    ) as XML
  ) 
FROM 
MY_TABLE
WHERE ID = 1
like image 154
semiintel Avatar answered Oct 01 '22 23:10

semiintel


In similar situation, where I had to retrieve xml data, this worked for me

select my_id, cast(xmlserialize(my_column as clob(1m)) as varchar(20000)) from schema.my_table where my_id  =  463

earlier I was able to do this in squirrel sql without the CAST but latest version I had to use the cast

like image 43
Kalpesh Soni Avatar answered Oct 02 '22 00:10

Kalpesh Soni


As far as I know there is no way to get around the 32k limit, if you use it in SQL selects like you described.

If you use JDBC to retrieve your data, instead of using getString() on the result set, you get a CLOB handle, and from that you can get a stream.

On the other hand, is it really a limit? Do you really use CLOBs in where clauses etc.? A RDBMS is optimized for smaller row sizes to be handled in transactions efficiently.

Generally speaking, stream the data. Consider redesigning your data model, if this CLOB contains data which can be split into multiple columns, and you need some of its data in your query (where ..., order by ... etc.).

like image 43
Beryllium Avatar answered Oct 02 '22 01:10

Beryllium