by Kevin Loney
Oracle Press. (c) 2009. Copying Prohibited.
Oracle Database 11g: The Complete Reference
In place of LONG and LONG RAW, you can use the LOB datatypes (BLOB, CLOB, NCLOB, and BFILE) for storage of long data. Although
Oracle still allows LONG and LONG RAW columns to be created, Oracle recommends that you create new columns using the LOB datatypes and that you convert existing LONG and LONG RAW columns to CLOB or BLOB columns, respectively. If you use one of these datatypes to store large objects (LOBs), you can take advantage of new capabilities for viewing and manipulating the data. You can also use Oracle Text
(see Chapter 27) to perform text searches on CLOB data.
In this chapter, you will see how to use the LOB datatypes and how to manipulate the data — which does not even have to be stored within the database!
Four types of LOBs are supported:
LOB Datatype Description
BLOB Binary LOB. Binary data stored in the database.
CLOB
BFILE
NCLOB
Character LOB. Character data stored in the database.
Binary File. Read-only binary data stored outside the database, the length of which is limited by the operating system.
A CLOB column that supports a multibyte character set.
You can create multiple LOBs per table. For example, suppose you want to create a PROPOSAL table to track formal proposals you submit.
Your proposal records may consist of a series of word processing files and spreadsheets used to document and price the proposed work. The
PROPOSAL table will contain VARCHAR2 datatypes (for columns such as the name of the proposal recipient) plus LOB datatypes
(containing the word processing and spreadsheet files).
Note You cannot create multiple LONG or LONG RAW columns in a single table.
The create table command in the following listing creates the PROPOSAL table: create table PROPOSAL
(Proposal_ID NUMBER(10),
Recipient_Name VARCHAR2(25),
Proposal_Name VARCHAR2(25),
Short_Description VARCHAR2(1000),
Proposal_Text CLOB,
Budget BLOB,
Cover_Letter BFILE, constraint PROPOSAL_PK primary key (Proposal_ID));
Because you may submit multiple proposals to the same recipient, assign each proposal a Proposal_ID number. The PROPOSAL table stores the recipient of the proposal, the name of the proposal, and a short description. Then, taking advantage of the LOB datatypes available in Oracle, the PROPOSAL table includes three columns:
Proposal_Text A CLOB containing the text of the proposal
Budget A BLOB containing a spreadsheet showing calculations of the cost and profit for the proposed work
Cover_Letter A binary file (BFILE) stored outside the database that contains your cover letter that accompanies the proposal
Each row in the PROPOSAL table will have up to three LOB values stored. Oracle will use the normal database capabilities to support data integrity and concurrency for the Proposal and Budget entries, but not for the Cover_Letter values. Because the Cover_Letter column uses the
BFILE datatype, its data is stored outside the database. Internally, the database stores only a locator value that allows it to find the external file, thus reducing the space and management requirements for the database. Oracle does not guarantee the data integrity of BFILE files stored outside the database. Also, Oracle does not validate that these files exist when you insert a record using a BFILE datatype. Data concurrency and integrity are maintained only for internally stored LOBs.
The data for the LOB columns may be physically apart from the PROPOSAL table. Within the PROPOSAL table, Oracle stores locator values that point to data locations. For BFILE datatypes, the locator points to an external file; for BLOB and CLOB datatypes, the locator points to a separate data location that the database creates to hold the LOB data. The data location for the LOB data may be inline with the rest of the
PROPOSAL row or stored out of line. By default, the LOB data is stored inline if its length is less than approximately 4000 bytes.
Storing the data out of line allows the database to avoid having to scan the LOB data each time it reads multiple rows from the database. The
LOB data will only be read when it is required; otherwise, only its locator values will be read. You can specify the storage parameters
(tablespace and sizing) for the area used to hold the LOB data, as described in the
.
When you create a table that includes a LOB column, you can specify the storage parameters for the area used for the LOB data. Thus, for a table that has no LOB columns, you may have a storage clause in the create table command (see Chapter 17). If the table has at least one
Reprinted for F2ZK5/193522, SAIC
Page 2 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
LOB column, you also need an additional lob clause within your create table command.
Consider the PROPOSAL table, this time with a tablespace clause: create table PROPOSAL
(Proposal_ID NUMBER(10),
Recipient_Name VARCHAR2(25),
Proposal_Name VARCHAR2(25),
Short_Description VARCHAR2(1000),
Proposal_Text CLOB,
Budget BLOB,
Cover_Letter BFILE, constraint PROPOSAL_PK primary key (Proposal_ID))
tablespace PROPOSALS;
Because there are three LOB columns, the create table command should be modified to include the storage specifications for the out-of-line
LOB data (if you plan to store the LOB data out of line). Two of the LOB columns — Proposal_Text and Budget — will store data within the database. The revised version of the create table command, with the LOB storage clause specified, is shown in the following listing: create table PROPOSAL
(Proposal_ID NUMBER(10),
Recipient_Name VARCHAR2(25),
Proposal_Name VARCHAR2(25),
Short_Description VARCHAR2(1000),
Proposal_Text CLOB,
Budget BLOB,
Cover_Letter BFILE, constraint PROPOSAL_PK primary key (Proposal_ID))
tablespace PROPOSALS lob (Proposal_Text, Budget) store as
(tablespace Proposal_Lobs
storage (initial 100K next 100K pctincrease 0)
chunk 16K pctversion 10 nocache logging);
The last four lines of the create table command tell Oracle how to store the out-of-line LOB data. The instructions are as follows: lob (Proposal_Text, Budget) store as
(tablespace Proposal_Lobs
storage (initial 100K next 100K pctincrease 0)
chunk 16K pctversion 10 nocache logging);
The lob clause tells Oracle that the next set of commands deals with the out-of-line storage specifications for the table's LOB columns. The two
LOB columns (Proposal_Text and Budget) are explicitly listed. When the two columns' values are stored out of line, they are stored in a segment as specified via the lob clause: lob (Proposal_Text, Budget) store as
Note If there were only one LOB column, you could specify a name for the LOB segment. You would name the segment immediately after the store as clause in the preceding command.
The next two lines specify the tablespace and storage parameters for the out-of-line LOB storage. The tablespace clause assigns the out-ofline data to the PROPOSAL_LOBS tablespace, and an optional storage clause can be used to specify the initial, next , and pctincrease values the out-of-line data storage will use. See the entry for the storage clause in the Alphabetical Reference for an explanation of the available storage parameters for segments.
(tablespace Proposal_Lobs
Because the segments are for storing LOB data, several additional parameters are available, and they are specified within the lob clause: chunk 16K pctversion 10
The chunk LOB storage parameter tells Oracle how much space to allocate during each LOB value manipulation. The default chunk size is 1
KB, going up to a maximum value of 32KB.
The pctversion parameter is the maximum percentage of overall LOB storage space used for creating new versions of the LOB. By default, older versions of the LOB data will not be overwritten until 10 percent of the available LOB storage space is used.
The last two parameters of the LOB storage space tell Oracle how to handle the LOB data during reads and writes: nocache logging);
The nocache parameter in the lob storage clause specifies that the LOB values are not stored in memory for faster access during queries.
The default lob storage setting is nocache; its opposite is cache.
The logging parameter specifies that all operations against the LOB data will be recorded in the database's redo log files. The opposite of
Reprinted for F2ZK5/193522, SAIC
Page 3 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference logging, nologging , keeps operations from being recorded in the redo log files, thereby improving the performance of table-creation operations. You can also specify the tablespace and storage parameters for a LOB index. See the create table command entry in the
Alphabetical Reference for the full syntax related to LOB indexes.
If you specify cache and omit the nologging/logging clause, logging is automatically implemented because you cannot specify cache nologging. If cache is not specified and the nologging/logging clause is omitted, the logging value is obtained from the tablespace in which the LOB value is stored.
Now that the table has been created, you can begin to enter records into it. In the
next section , you will see how to insert LOB values into the
PROPOSAL table and how to use the DBMS_LOB package to manipulate the values.
You can have as many lob store as columns as you have LOB columns. Simply specify the LOB column name (or names) as part of the lob clause, as shown here: lob (Proposal_Text, Budget) store as
(tablespace Proposal_Lobs storage (initial 100K next 100K pctincrease 0) chunk 16K pctversion 10 nocache logging)
LOB data can be selected or manipulated in several ways. You can use the character string functions you would use on VARCHAR2 columns against LOB datatypes. For large LOB values (32KB or more in length), or for more complex operations against the data, you should manipulate LOB data via the DBMS_LOB package. Other methods for manipulating LOB data include using application programming interface (API) and Oracle Call Interface (OCI) programs. In this section, you will see the use of the string functions plus an overview of the
DBMS_LOB package. As these examples demonstrate, LOBs are much more flexible than LONG datatypes in terms of data-manipulation possibilities.
Table 40-1 lists the procedures and functions available via the DBMS_LOB package.
Table 40-1: DBMS_LOB Functions and Procedures
Subprogram
APPEND procedure
CLOSE procedure
COMPARE function
COPY procedure
FRAGMENT_MOVE procedure
FRAGMENT_REPLACE procedure
FREETEMPORARY procedure
GETCHUNKSIZE function
GETLENGTH function
GET_OPTIONS function
GET_STORAGE_LIMIT function
Description
Appends the contents of the source LOB to the destination LOB
Closes a previously opened internal or external LOB
Compares two entire LOBs or parts of two LOBs
Copies all, or part, of the source LOB to the destination LOB
CONVERTTOBLOB procedure Reads character data from a source CLOB or NCLOB instance, converts the character data to the specified character, writes the converted data to a destination BLOB instance in binary format, and returns the new offsets
CONVERTOCLOB procedure Reads character data from a source CLOB or NCLOB instance, converts the character data to the specified character, writes the converted data to a destination BLOB instance in binary format, and returns the new offsets
Creates a temporary BLOB or CLOB and its corresponding index in the user's default temporary tablespace CREATETEMPORARY procedure
ERASE procedure
FILECLOSE procedure
FILECLOSEALL procedure
Erases all or part of a LOB
Closes the file
Closes all previously opened files
FILEEXISTS function
FILEGETNAME procedure
FILEISOPEN function
FILEOPEN procedure
FRAGMENT_DELETE procedure
FRAGMENT_INSERT procedure
Checks whether the file exists on the server
Gets the directory alias and filename
Checks whether the file was opened using the input BFILE locators
Opens a file
Deletes the data at the given offset for the given length within the LOB
Inserts the data at the given offset (limit 32KB) within the LOB
Moves the amount of bytes (BLOB) or characters (CLOB/NCLOB) from the given offset to the new offset specified
Replaces the data at the given offset with the given data (not to exceed 32KB)
Frees the temporary BLOB or CLOB in the user's default temporary tablespace
Returns the amount of space used in the LOB chunk to store the LOB value
Gets the length of the LOB value
Obtains settings corresponding to the option_types field for a particular LOB
Returns the storage limit for LOBs in your database configuration
Reprinted for F2ZK5/193522, SAIC
Page 4 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
INSTR function
ISOPEN function
ISTEMPORARY function
LOADFROMFILE procedure
LOADBLOBFROMFILE procedure
LOADCLOBFROMFILE procedure
OPEN procedure
READ procedure
SETOPTIONS procedure
SUBSTR function
TRIM procedure
WRITE procedure
WRITEAPPEND procedure
Returns the matching position of the nth occurrence of the pattern in the LOB
Checks to see whether the LOB was already opened using the input locator
Checks whether the locator is pointing to a temporary LOB
Loads BFILE data into an internal LOB
Loads BFILE data into an internal BLOB
Loads BFILE data into an internal CLOB
Opens a LOB (internal, external, or temporary) in the indicated mode
Reads data from the LOB starting at the specified offset
Enables CSCE features on a per-LOB basis, overriding the default LOB column settings
Returns part of the LOB value starting at the specified offset
Trims the LOB value to the specified shorter length
Writes data to the LOB from a specified offset
Writes a buffer to the end of a LOB
Consider the PROPOSAL table again. The Proposal_ID column is the primary key column for the PROPOSAL table. The PROPOSAL table contains three LOB columns — one BLOB, one CLOB, and one BFILE. For each of the LOB columns, Oracle will store a locator value that tells it where to find any out-of-line data stored for the record.
When you insert a record into a table that contains LOBs, you use functions to tell Oracle to create an empty locator value for the internally stored LOB columns. An empty locator value is different from a NULL value. If an internally stored LOB column's value is NULL , you have to set it to an empty locator value before updating it to a nonNULL value.
Suppose you begin to work on a proposal and enter a record in the PROPOSAL table. At this point, you have neither a budget spreadsheet nor a cover letter. The insert command is shown in the following listing: insert into PROPOSAL
(Proposal_ID, Recipient_Name, Proposal_Name, Short_Description,
Proposal_Text,
Budget, Cover_Letter) values
(1, 'DOT RODALE', 'MAINTAIN ORGANIC GARDEN', NULL,
'This is the text of a proposal to maintain an organic garden.',
EMPTY_BLOB(),NULL);
The inserted record has a Proposal_ID value of 1 and a RecipientName value of DOT RODALE. The Proposal_Name value is MAINTAIN
ORGANIC GARDEN and the Short_Description column is left NULL for now. The Proposal_Text column is set equal to a short character string for now. To set the Budget column to an empty locator value, you use the EMPTY_BLOB function. If you had wanted to set a CLOB datatype column equal to an empty locator value, you would have used the EMPTY_CLOB function. The Cover_Letter column, because it is an externally stored BFILE value, is set to NULL.
To set a LOB column to an empty locator value, you have to know its datatype:
BLOB Use EMPTY_BLOB()
CLOB Use EMPTY_CLOB()
NCLOB Use EMPTY_CLOB()
BFILE Use BFILENAME
You use the BFILENAME procedure to point to a directory and filename combination. Before entering a value for the directory in the
BFILENAME function, a user with the DBA role or the CREATE ANY DIRECTORY system privilege must create the directory. To create a directory, use the create directory command, as shown in the following example: create directory proposal_dir as '/uOl/proposal/letters';
When inserting BFILE entries, you refer to the logical directory name — such as proposal_dir — instead of the physical directory name on the operating system. Users with DBA authority can grant READ access to the directory names to users. See the entry for the create directory command in the Alphabetical Reference for further details.
You can now enter a second PROPOSAL record; this record will have a Cover_Letter value: insert into PROPOSAL
(Proposal_ID, Recipient_Name, Proposal_Name, Short_Description,
Proposal_Text, Budget,
Cover_Letter)
Reprinted for F2ZK5/193522, SAIC
Page 5 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference values
(2, 'BRAD OHMONT', 'REBUILD FENCE', NULL,
EMPTY_CLOB(), EMPTY_BLOB(),
BFLLENAME('proposal_dir','P2.DOC));
In this listing, a second proposal — rebuilding a fence — is inserted into the PROPOSAL table. The EMPTY_CLOB() and EMPTY_BLOB() functions are optionally used to insert empty locator values in the table. The BFILENAME function tells Oracle exactly where to find the cover letter — it's in the proposaldir directory and its name is P2.DOC. Within the BFILENAME function, the first parameter is always the directory name, and the second parameter is the name of the file within that directory.
Note The P2.DOC file does not have to exist for this record to be inserted successfully.
When you select the value from a LOB column, Oracle uses the locator value to find the data that is associated with the LOB data. You never need to know or specify the locator values. And, as you'll see in the following sections, you can do things with LOB values that are impossible to do with LONG datatypes.
What if you want to duplicate a proposal record? For example, suppose you begin to work on a third proposal, and it is very similar to the first proposal: insert into PROPOSAL
(Proposal_ID, Recipient_Name, Proposal_Name, Short_Description,
Proposal_Text, Budget, Cover_Letter) select 3, 'SKIP GATES', 'CLEAR GATES FIELD', NULL,
Proposal_Text, Budget, Cover_Letter
from PROPOSAL
where Proposal_ID = 1;
This insert command tells Oracle to find the PROPOSAL record with a Proposal_ID value of 1. Take the Proposal_Text, Budget, and
Cover_Letter column values and the literal values specified (3, SKIP GATES, and so forth) and insert a new record into the PROPOSAL table.
Note that the inserted LOB columns will be set to empty locator values. The ability to perform inserts based on queries is a significant advantage of using LOB datatypes — you cannot perform this type of insert if a LONG column is part of the query.
Note If you use insert as select to populate LOB values, you may have multiple BFILE values pointing to the same external file. You may need to update the new values to point to the correct external files. Oracle does not maintain data integrity for the external files.
In the third record that was created, the Proposal_Text value was copied from the first record. To update the Proposal_Text value of the record that has a Proposal_ID of 3, execute the following command: update PROPOSAL
set Proposal_Text = 'This is the new proposal text.' where Proposal_ID = 3;
You can also update the Cover_Letter column to point to the correct cover letter. Use the BFILENAME function to point to the correct file: update PROPOSAL
set Cover_Letter = BFILENAME('proposal_dir', 'P3.DOC') where Proposal_ID = 3;
You can update NULL values of BFILE columns without first setting them to empty locator values.
You can use the Oracle-provided string functions against CLOB values. For example, you can use SUBSTR, INSTR, LTRIM , and INITCAP to modify the strings. See Chapter 7 for descriptions of the built-in string functions.
In the PROPOSAL table, the Proposal_Text column is defined as a CLOB datatype. Here are the three Proposal_Text values (the second is
NULL): select Proposal_Text from PROPOSAL;
PROPOSAL_TEXT
------------------------------------------------------------
This is the text of a proposal to maintain an organic garden.
This is the new proposal text.
Applying INITCAP to the third record yields this result: select INITCAP (Proposal_Text) from PROPOSAL
Reprinted for F2ZK5/193522, SAIC
Page 6 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference where Proposal_ID = 3;
INITCAP(PROPOSAL_TEXT)
-------------------------------------------------------
This Is The New Proposal Text.
Applying INSTR to all three rows returns the expected result: select INSTR(Proposal_Text,'new',1,1) from PROPOSAL;
INSTR(PROPOSAL TEXT,'NEW,1,1)
---------------------------------------------------------
0
0
13
You can use SUBSTR to return the first ten characters of the text: select SUBSTR(Proposal_Text,1,10) from PROPOSAL where Proposal_ID = 3;
SUBSTR(PROPOSAL_TEXT,1,10)
--------------------------------------------------------------
This is th
For complex manipulations, you should use the DBMS_LOB package, as described in the following sections.
Note The regular expression functions (see Chapter 8) may be used against LOB datatypes.
You can use the DBMS_LOB package to change or select LOB values. In the following sections, you will see how to perform SQL functions such as SUBSTR and INSTR on LOB values, as well as how to append to LOB values, compare LOB values, and read LOB values.
The string comparison and manipulation procedures and functions available within the DBMS_LOB package are listed in
The major procedures and functions available within the DBMS_LOB package are described in the following sections. When using BFILEs, the maximum number of files you can concurrently have open is limited by the setting of the SESSION_MAX_OPEN_FILES parameter in the database's system parameter file. The default maximum number of concurrently open BFILE files is 10; the maximum is either 50 or the value of the MAX_OPEN_FILES parameter, whichever is lower.
Note For the full listing of all DBMS_LOB subprograms, see the Oracle documentation set. The functions and procedures described in this chapter are the ones expected to be most frequently used by developers.
In the following examples, the Proposal_Text CLOB column is used to show the impact of the major procedures and functions.
READ
The READ procedure reads a piece of a LOB value. In the PROPOSAL table example, the Proposal_Text for the first row is select Proposal_Text from PROPOSAL where Proposal_ID = 1;
PROPOSAL_TEXT
-------------------------------------------------------------------------
This is the text of a proposal to maintain an organic garden.
This is a fairly short description, so it could have been stored in a VARCHAR2 datatype column. Because it is stored in a CLOB column, though, its maximum length is much greater than it would have been if it had been stored in a VARCHAR2 column. The maximum size for both
BLOBs and CLOBs is defined via the formula (4GB - 1) * database block size, yielding values between 8TB and 128TB. For these examples, we'll use this short string for purposes of demonstration; you can use the same functions and operations against longer CLOB strings, as well.
The READ procedure has four parameters, which must be specified in this order:
1. The LOB locator (for either a BLOB, CLOB, or BFILE)
2. The number of bytes or characters to be read
3. The offset (starting point of the read) from the beginning of the LOB value
4. The output data from the READ procedure
If the end of the LOB value is reached before the specified number of bytes is read, the READ procedure will return an error.
Reprinted for F2ZK5/193522, SAIC
Page 7 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
Because the READ procedure requires the LOB locator as input, the READ procedure is executed within PL/SQL blocks. You will need to select the LOB locator value, provide that as input to the READ procedure, and then display the text read via the DBMS_OUTPUT package.
A Word About the DBMS_OUTPUT Package As noted in Chapter 35, you can use the DBMS_OUTPUT package to display the values of variables within a PL/SQL block. The PUT_LINE procedure within DBMS_OUTPUT displays the specified output on a line. Before using the
DBMS_OUTPUT package, you should first execute the set serveroutput on
, you'll see how to create the
PL/SQL block that will read the data from a LOB.
A READ Example To use the READ procedure, you need to know the locator value of the LOB you want to read. The locator value must be selected from the table that contains the LOB. Because the locator value must be supplied as input to the READ procedure, you should use
PL/SQL variables to hold the locator value. The READ procedure, in turn, will place its output in a PL/SQL variable. You can use the
DBMS_OUTPUT package to display the output value. The structure of the PL/SQL block for this example is as follows: declare variable to hold locator value variable to hold the amount (the number of characters/bytes to read) variable to hold the offset variable to hold the output begin set value for amount_var; set value for offset_var; select locator value into locator var from table;
DBMS_LOB.READ
(locator var, amount var, offset var, output var);
DBMS_OUTPUT.PUT_LINE('Output: ' || output var); end;
Note See Chapter 32 for an overview of PL/SQL blocks and their components.
For the PROPOSAL table, selecting the first ten characters from the Proposal_Text column would look like this: declare
locator_var CLOB;
amount_var INTEGER;
offset_var INTEGER;
output_var VARCHAR2(10); begin
amount_var := 10;
offset_var := 1;
select Proposal_Text into locator_var
from PROPOSAL
where Proposal_ID = 1;
DBMS_LOB.READ(locator_var, amount_var, offset_var, output_var);
DBMS_OUTPUT.PUT_LINE('Start of proposal text: ' || output_var); end;
/
When you execute the preceding PL/SQL block, the output will match the SQL SUBSTR example shown earlier: start of proposal text: This is th
PL/SQL procedure successfully completed.
The output shows the first ten characters of the Proposal_Text value, starting at the first character of the LOB value.
The PL/SQL block in the preceding example first declared the variables to use: declare locator_var CLOB; amount_var INTEGER; offset_var INTEGER; output_var VARCHAR2(10);
Next, values were assigned to the variables: begin amount_var := 10; offset_var := 1;
Then the locator value was selected from the table and stored in a variable named locator_var: select Proposal_Text into locator_var from PROPOSAL where Proposal_ID = 1;
Next, the READ procedure was called, using the values that had been assigned so far:
Reprinted for F2ZK5/193522, SAIC
Page 8 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
DBMS_LOB.READ(locator_var, amount_var, offset_var, output_var);
As a result of the execution of the READ procedure, the output_var variable will be populated with the data that was read. The PUT_LINE procedure displays that data:
DBMS_OUTPUT.PUT_LINE('Start of proposal text: ' I I output_var);
This format for PL/SQL blocks will be used throughout the rest of this chapter. You can optionally set the variable values when they are declared.
If you want to select a different portion of the Proposal_Text CLOB, just change the amount and offset variables. If you change the number of characters read, you need to change the size of the output variable, too. In the following example, 12 characters are read from Proposal_Text, starting from the tenth character: declare locator_var CLOB; amount_var INTEGER; offset_var INTEGER;
output_var VARCHAR2(12); begin amount_var := 12; offset_var := 10; select Proposal_Text into locator_var from PROPOSAL where Proposal_ID = 1;
DBMS_LOB.READ(locator_var, amount_var, offset_var, output_var);
DBMS_OUTPUT.PUT_LINE('Part of proposal text: ' I I output_var); end;
/
Output from this PL/SQL block is shown in the following listing:
Part of proposal text: he text of a
PL/SQL procedure successfully completed.
If Proposal_Text had been created as a VARCHAR2 column, you could have selected this data using the SUBSTR function. However, you would have been limited to a maximum column length of 4,000 characters. Also, note that the LOB column can contain binary data (BLOB datatypes), and you can use the READ procedure to select data from BLOBs in the same way you select from CLOBs. For BLOBs, you should declare the output buffer to use the RAW datatype. In PL/SQL, RAW and VARCHAR2 datatypes (used for the output variables for CLOB and
BLOB reads) have a maximum length of 32,767 characters.
For the READ procedure, possible exceptions are VALUE_ERROR, INVAUD_ARGVAL, NO_ DATA_FOUND, UNOPENED_FILE,
NOEXIST_DIRECTORY, NOPRIV_DIRECTORY, INVALID_DIRECTORY, INVALID_OPERATION, and BUFFERING_ENABLED.
SUBSTR
The SUBSTR function within the DBMS_LOB package performs the SQL SUBSTR function on a LOB value. This function has three input parameters, which must be specified in this order:
1. The LOB locator
2. The number of bytes or characters to be read
3. The offset (starting point of the read) from the beginning of the LOB value
Because SUBSTR is a function, there is no output variable value returned directly from SUBSTR as there was with READ. For the READ procedure, you declared an output variable and then populated it within the READ procedure call. The PL/SQL block used for the READ procedure is shown in the following listing, with the lines related to the output variable shown in bold: declare
locator_var CLOB;
amount_var INTEGER;
offset_var INTEGER; output_var VARCHAR2(12); begin
amount_var := 12;
offset_var := 10;
select Proposal_Text into locator_var
from PROPOSAL
where Proposal_ID = 1;
DBMS_LOB.READ(locator_var, amount_var, offset_var, output_var);
DBMS_OUTPUT.PUT_LINE('Section of proposal text: ' || output_var); end;
Reprinted for F2ZK5/193522, SAIC
Page 9 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
/
Because SUBSTR is a function, you will populate the output variable differently. The format is output_var := DBMS_LOB.SUBSTR(locator_var, amount_var, offset_var);
The preceding PL/SQL statement uses the SUBSTR function of the DBMS_LOB package to select 12 characters from the Proposal_Text
LOB column, starting at the tenth character. The full PL/SQL block is declare
locator_var CLOB;
amount_var INTEGER;
offset_var INTEGER;
output_var VARCHAR2(12); begin
amount_var := 12;
offset_var := 10;
select Proposal_Text into locator_var
from PROPOSAL
where Proposal_ID = 1;
output_var := DBMS_LOB.SUBSTR(locator_var, amount_var, offset_var);
DBMS_OUTPUT.PUT_LINE('Section of proposal text: ' || output_var); end;
/
The output is shown in the following listing:
Section of proposal text: he text of a
PL/SQL procedure successfully completed.
The equivalent SQL function call is select SUBSTR(Proposal_Text, 10, 12) from PROPOSAL where Proposal_ID = 1;
The SUBSTR example differs from the READ example in only two ways: the name of the function call, and the manner of assigning a value to the output variable. As with the READ procedure example, the PUT_LINE procedure of the DBMS_OUTPUT package is used to display the results.
In general, you should use the SUBSTR function whenever you are interested in selecting only a specific section of the LOB value. The READ function can be used to select only a portion of a text string (as in the previous examples), but it is more often used within a loop. For example, suppose the LOB value is larger than the largest allowed RAW or VARCHAR2 variable in PL/SQL (32,767 characters). In that case, you can use the READ procedure within a loop to read all the data from the LOB value. Refer to Chapter 32 for details on the different loop options available in PL/SQL.
For the SUBSTR function, possible exceptions are UNOPENED_FILE, NOEXIST_DIRECTORY, NOPRIV_DIRECTORY,
INVALID_DIRECTORY, INVAUD_OPERATION, and BUFFERING_ENABLED.
INSTR
The INSTR function within the DBMS_LOB package performs the SQL INSTR function on a LOB value.
The INSTR function has four input parameters, which must be specified in this order:
1. The LOB locator
2. The pattern to be tested for (RAW bytes for BLOBs, character strings for CLOBs)
3. The offset (starting point of the read) from the beginning of the LOB value
4. The occurrence of the pattern within the LOB value
The INSTR function within DBMS_LOB searches the LOB for a specific pattern of bytes or characters. The occurrence variable allows you to specify which occurrence of the pattern within the searched value should be returned. The output of the INSTR function is the position of the start of the pattern within the searched string. For example, in SQL,
1 means that within the string ABCABC, the pattern A is searched for, starting at the first position of the string, and looking for the first occurrence. The A is found in the first position of the searched string. If you start the search at the second position of the string, the answer will be different:
4
Because this INSTR starts at the second position, the first A is not part of the value that is searched. Instead, the first A found is the one in the
Reprinted for F2ZK5/193522, SAIC
Page 10 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference fourth position.
If you change the last parameter in the SQL INSTR to look for the second occurrence of the string A , starting at the second position, the pattern is not found:
0
If the SQL INSTR function cannot find the matching occurrence of the pattern, 0 is returned. The INSTR function of the DBMS_LOB package operates in the same manner.
Because INSTR is a function, you need to assign its output variable in the same manner as the SUBSTR function's output variable was assigned. In the following listing, the Proposal_Text CLOB value is searched for the string ‘ pr ’ . The position_var variable is declared to hold the output of the INSTR function.
declare
locator_var CLOB;
pattern_var VARCHAR2(2);
offset_var INTEGER;
occur_var INTEGER;
position_var INTEGER; begin
pattern_var := 'pr';
offset_var := 1;
occur_var := 1;
select Proposal_Text into locator_var
from PROPOSAL
where Proposal_ID = 1;
position_var := DBMS_LOB.INSTR(locator_var, pattern_var, offset_var, occur_var);
DBMS_OUTPUT.PUT_LINE('Found string at position: ' || position_var); end;
/
The output would be
Found string at position: 23
PL/SQL procedure successfully completed.
The output shows that the search string ‘ pr ’ is found within the Proposal_Text, starting at the 23rd character of the LOB value. Because Oracle supports SQL string functions against CLOB columns, this function call is equivalent to the following query: select INSTR(Proposal_Text , 'pr',1,1) from PROPOSAL where Proposal_ID = 1;
For the INSTR function, possible exceptions are UNOPENED_FILE, NOEXIST_DIRECTORY, NOPRIV_DIRECTORY, I NVAUD_DI
RECTORY, INVAUD_OPERATION, and BUFFERING_ENABLED.
GETLENGTH
The GETLENGTH function of the DBMS_LOB package returns the length of the LOB value. The DBMS_LOB.GETLENGTH function is similar in function to the SQL LENGTH function, but it's used only for LOB values.
The GETLENGTH function of the DBMS_LOB package has only one input parameter: the locator value for the LOB. In the following listing, variables are declared to hold the locator value and the output value. The GETLENGTH function is then executed, and the result is reported via the PUT_LINE procedure: declare
locator_var CLOB;
length_var INTEGER; begin
select Proposal_Text into locator_var
from PROPOSAL
where Proposal_ID = 1;
length_var := DBMS_LOB.GETLENGTH(locator_var);
DBMS_OUTPUT.PUT_LINE('Length of LOB: ' || length_var); end;
/
The following is the GETLENGTH output:
Length of LOB: 61
PL/SQL procedure successfully completed.
Reprinted for F2ZK5/193522, SAIC
Page 11 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
If the LOB value is NULL , the GETLENGTH function will return a value of NULL.
The equivalent SQL function for CLOB values is select LENGTH(Proposal_Text) from PROPOSAL where Proposal_ID = 1;
COMPARE
The COMPARE function of the DBMS_LOB package compares two LOB values. If the two LOB values are the same, the COMPARE function returns 0; otherwise, it returns a nonzero integer value (usually 1 or-1). To execute the COMPARE function, the DBMS_LOB package essentially performs two READ functions and compares the results. Thus, for each of the LOB values to be compared, you need to supply a locator value and an offset value; the number of characters or bytes to be compared will be the same for both LOB values. You can only compare LOBs of the same datatype.
The COMPARE function has five input parameters, which must be specified in this order:
1. The LOB locator for the first LOB
2. The LOB locator for the second LOB
3. The amount variable (the number of bytes or characters to compare)
4. The offset (starting point of the read) from the beginning of the first LOB value
5. The offset (starting point of the read) from the beginning of the second LOB value
Because the two LOBs being compared can have different offset values, you can compare the first part of one LOB value with the second part of a different LOB value. The example in the following listing compares the first 25 characters of the Proposal_Text values from two entries — the Proposal_ID 1 record and the Proposal_ID 3 record: declare
first_locator_var CLOB;
second_locator_var CLOB;
amount_var INTEGER;
first_offset_var INTEGER;
second_offset_var INTEGER;
output_var INTEGER; begin
amount_var := 25;
first_offset_var := 1;
second_offset_var := 1;
select Proposal_Text into first_locator_var
from PROPOSAL
where Proposal_ID = 1;
select Proposal_Text into second_locator_var
from PROPOSAL
where Proposal_ID = 3;
output_var :=DBMS_LOB.COMPARE(first_locator_var, second_locator_var,
amount_var, first_offset_var, second_offset_var);
DBMS_OUTPUT.PUT_LINE('Comparison value (0 if the same): '||
output_var); end;
/
The following is the output:
Comparison value (0 if the same): 1
PL/SQL procedure successfully completed.
If the two strings are the same, the COMPARE function will return 0.
In the following listing, the same two LOBs are compared, but this time only their first five characters are used for the comparison. Because both start with the characters "This", the COMPARE will return 0: declare first_locator_var CLOB; second_locator_var CLOB; amount var INTEGER; first_offset_var INTEGER; second_offset_var INTEGER; output_var INTEGER; begin
Reprinted for F2ZK5/193522, SAIC
Page 12 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference amount_var := 5; first_offset_var := 1; second_offset_var := 1; select Proposal_Text into first_locator_var from PROPOSAL where Proposal_ID = 1; select Proposal_Text into second_locator_var from PROPOSAL where Proposal_ID = 3; output_var :=DBMS_LOB.COMPARE(first_locator_var, second_locator_var,
amount_var, first_offset_var, second_offset_var);
DBMS_OUTPUT.PUT_LINE('Comparison value (0 if the same):' || output_var); end;
/
Comparison value (0 if the same): 0
PL/SQL procedure successfully completed.
The COMPARE function allows you to compare character strings to character strings and compare binary data to binary data. If you are using the COMPARE function on BLOB columns, you should define the locator variables as RAW datatypes.
For the COMPARE function, possible exceptions are UNOPENED_FILE, NOEXIST_DIRECTORY, NOPRIV_DIRECTORY,
INVALID_DIRECTORY, INVAUD_OPERATION, and BUFFERING_ENABLED.
WRITE
The WRITE procedure of the DBMS_LOB package allows you to write data in specific locations of the LOB. For example, you can write binary data into a section of a BLOB, overwriting the existing data there. You can write character data into CLOB fields using the WRITE procedure.
This procedure has four input parameters, which must be specified in this order:
1. The LOB locator for the LOB
2. The amount variable (the number of bytes or characters to write)
3. The offset (starting point of the write) from the beginning of the LOB value
4. The buffer variable assigned to the character string or binary data being added
Because the WRITE procedure updates the LOB value, you should first lock the row via a select for update , as shown in bold in the following listing. In this example, a record is selected and locked. The text ADD NEW TEXT is then written to the LOB value, overwriting the data starting in position 10 (as defined by the offset variable).
declare locator_var CLOB; amount_var INTEGER; offset_var INTEGER; buffer var VARCHAR2(12); begin
amount_var := 12;
offset_var := 10;
buffer_var := 'ADD NEW TEXT'; select Proposal_Text into locator_var
from PROPOSAL
where Proposal_ID = 3 for update;
DBMS_LOB.WRITE(locator_var, amount_var, offset_var, buffer_var); commit; end;
/
Because the WRITE procedure changes the data, a commit command is added before the end clause of the PL/SQL block.
Note Test without a commit first so you can see the impact of your procedure call before committing the change to the database.
For the WRITE procedure, no output is provided. To see the changed data, you need to either call the READ procedure (within the same
PL/SQL block, if you want) or select the LOB value from the table again: select Proposal_Text from PROPOSAL where Proposal_ID = 3;
Reprinted for F2ZK5/193522, SAIC
Page 13 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
PROPOSAL_TEXT
---------------------------------------------------------------
This is tADD NEW TEXTsal text.
The WRITE procedure overwrote 12 characters, starting at the tenth character of ProposaL Text. You can use the WRITEAPPEND procedure to append new data to the end of an existing LOB value.
For CLOB data, you can rewrite this using an update statement combined with SUBSTR and concatenation functions.
For the WRITE function, possible exceptions are VALUE_ERROR, INVAUD_ARGVAL, QUERY_ WRITE, BUFFERING_ENABLED, and
SECUREFILE_OUTOFBOUNDS.
APPEND
The APPEND procedure of the DBMS_LOB package appends data from one LOB to a second LOB. Because this amounts to an update of a
LOB value, the record being updated should be locked prior to executing the APPEND procedure.
The APPEND procedure takes only two parameters: the locator value for the destination LOB, and the locator value for the source LOB. If either parameter is NULL , the APPEND procedure will return an error.
In the following example, two locator variables are defined. The first locator variable is named dest_locator_var; this is the locator value for the
LOB into which the data is to be appended. The second locator variable, source_locator_var , is the locator value for the source data that is to be appended to the destination LOB. The destination LOB, because it is being updated, is locked via a select for update command. In this example, the Proposal_Text value for the Proposal_ID 1 record is appended to the Proposal_Text value for the Proposal_ID 3 record: declare
dest_locator_var CLOB;
source_locator_var CLOB; begin
select Proposal_Text into dest_locator_var
from PROPOSAL
where Proposal_ID = 3
for update;
select Proposal_Text into source_locator_var
from PROPOSAL
where Proposal_ID = 1;
DBMS_LOB.APPEND(dest_locator_var, source_locator_var); commit; end;
/
To see the changed data, you can select the record from the PROPOSAL table: select Proposal_Text
from PROPOSAL
where Proposal_ID = 3;
PROPOSAL_TEXT
---------------------------------------------------------------
This is tADD NEW TEXTsal text.This is the text of a proposal to maintain an orga
What happened to the rest of the text? By default, only 80 characters of LONG and LOB values are displayed during queries. To see the rest of the text, use the set long command: set long 1000 select Proposal_Text
from PROPOSAL
where Proposal_ID = 3;
PROPOSAL_TEXT
---------------------------------------------------------------
This is tADD NEW TEXTsal text.This is the text of a proposal to maintain an organic garden.
In this example, the first 1,000 characters of the LOB value were displayed. If you need to know how long the LOB is, use the GETLENGTH function, as described earlier in this chapter.
In addition to allowing you to append CLOB values, the APPEND procedure allows you to append BLOB values. When appending BLOB
Reprinted for F2ZK5/193522, SAIC
Page 14 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference data, you need to be aware of the format of the BLOB data and the impact of appending new data on the end of the BLOB value. For BLOB values, the APPEND function may be most useful for applications in which the BLOB contains only raw data (such as digital data transmissions) rather than formatted binary data (such as spreadsheet files formatted by a program).
For CLOB data, you could rewrite this with an update statement, setting the Proposal_Text value equal to the concatenation of multiple values.
For the APPEND procedure, VALUE_ERROR, QUERY_WRITE, and BUFFERING_ENABLED are the defined exceptions.
ERASE
You can use the ERASE procedure of the DBMS_LOB package to erase the characters or bytes in any part of a LOB. You can use ERASE to erase the entire LOB value, or you can specify which section of the LOB to erase. ERASE is similar in function to WRITE. If you erase data in a
BLOB value, the data is replaced with zero-byte filler. If you erase data in a CLOB value, spaces are inserted into the CLOB.
Because you are updating a LOB value, you should follow the standard procedures for LOB updates: Lock the row and commit when the procedure has completed.
In the following PL/SQL block, a portion of Proposal_Text for the record with Proposal_ID 3 is erased. The erased characters will start at an offset of 10 and continue for 1 7 characters. The parameters for the ERASE procedure, in order, are
1. The LOB locator for the LOB
2. The amount variable (the number of bytes or characters to erase)
3. The offset (starting point of the erasure) from the beginning of the LOB value declare
locator_var CLOB;
amount_var INTEGER;
offset_var INTEGER; begin
amount_var := 17;
offset_var := 10;
select Proposal_Text into locator_var
from PROPOSAL
where Proposal_ID = 3
for update;
DBMS_LOB.ERASE(locator_var, amount_var, offset_var); commit; end;
/
4. The change to the record can be seen by querying the Proposal_Text value: select Proposal_Text
from PROPOSAL
where Proposal_ID = 3;
PROPOSAL_TEXT
---------------------------------------------------------------
This is t ext.This is the text of a proposal to maintain an organic garden.
Note The space previously held by the erased data is replaced by blanks; the rest of the data in the LOB does not change its position.
For CLOB data, you can rewrite this operation using an update statement, setting a new value for Proposal_Text by concatenating SUBSTR results and a blank string.
For the ERASE procedure, possible exceptions are VALUE_ERROR, INVALID_ARGVAL, QUERY_ WRITE, and BUFFERING_ENABLED.
TRIM
You can use the TRIM procedure of the DBMS_LOB package to reduce the size of a LOB value by trimming characters or bytes from the end of the value (like the SQL RTRIM function). When the TRIM procedure is executed, you specify the locator value for the LOB and the LOB's new length.
In the following listing, the Proposal_Text for the Proposal_ID 3 record is trimmed to its first ten characters. Because the TRIM procedure changes the data, a commit command is added before the end clause of the PL/SQL block.
declare
locator_var CLOB;
new_length_var INTEGER; begin
new_length_var := 10;
Reprinted for F2ZK5/193522, SAIC
Page 15 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
select Proposal_Text into locator_var
from PROPOSAL
where Proposal_ID = 3
for update;
DBMS_LOB.TRIM(locator_var, new_length_var); commit; end;
/
For the TRIM procedure, no output is provided. To see the changed data, you need to select the LOB value from the table again: select Proposal_Text
from PROPOSAL
where Proposal_ID = 3;
PROPOSAL_TEXT
------------------------------------------------------------------
This is t
The sample output shows the results of the TRIM procedure following the ERASE procedure executed in the preceding section. For CLOB data, you could rewrite this as a simple update: update PROPOSAL
set Proposal_Text = SUBSTR(Proposal_Text,1,10) where Proposal_ID = 3;
For the TRIM procedure, possible exceptions are VALUE_ERROR, INVALID_ARGVAL QUERY_WRITE, and BUFFERING_ENABLED.
COPY
You can use the COPY procedure of the DBMS_LOB package to copy data from a part of one LOB into a second LOB. Unlike with the
APPEND procedure, you do not have to copy the full text of one LOB value into another. During the COPY procedure, you can specify the offset to read from and the offset to write to. The five parameters of the COPY procedure are, in order:
1. The destination LOB locator
2. The source LOB locator
3. The amount (the number of characters or bytes to copy)
4. The offset to start writing to within the destination LOB value
5. The offset to start reading from within the destination LOB value
COPY is a combination of the READ and WRITE capabilities. Like the WRITE operation, the COPY procedure modifies the LOB value.
Therefore, the record should first be locked, and the PL/SQL block must contain a commit command. In the following example, the first 61 characters of the Proposal_ID 1 record are copied to the Proposal_ID 3 record. Because the destination LOB uses an offset of 1, the copied data will overwrite data within the destination LOB.
declare
dest_locator_var CLOB;
source_locator_var CLOB;
amount_var INTEGER;
dest_offset_var INTEGER;
source_offset_var INTEGER; begin
amount_var := 61;
dest_offset_var := 1;
source_offset_var := 1;
select Proposal_Text into dest_locator_var
from PROPOSAL
where Proposal_ID = 3
for update;
select Proposal_Text into source_locator_var
from PROPOSAL
where Proposal_ID = 1;
DBMS_LOB.COPY(dest_locator_var, source_locator_var,
amount_var, dest_offset_var, source_offset_var); commit; end;
/
The COPY procedure displays no output. To see the changed data, you need to select the LOB value from the table again:
Reprinted for F2ZK5/193522, SAIC
Page 16 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference select Proposal_Text
from PROPOSAL
where Proposal_ID = 3;
PROPOSAL_TEXT
-------------------------------------------------------------
This is the text of a proposal to maintain an organic garden.
For the COPY procedure, possible exceptions are VALUE_ERROR, INVALID_ARGVAL, QUERY_WRITE, and BUFFERING_ENABLED.
Using the BFILE Functions and Procedures
Because BFILE values are stored externally, several functions and procedures are used to manipulate the files prior to executing READ,
SUBSTR, INSTR, GETLENGTH, or COMPARE operations on BFILE LOBs. The BFILE-related procedures and functions within DBMS_LOB,
, allow you to open files, close files, get the filename, check whether a file exists, and check whether a file is open.
The existence-check function is necessary because Oracle does not maintain the data stored in the external file; Oracle only maintains the
record, you would open the file and then execute the READ procedure. The PUT_LINE procedure of the DBMS_OUTPUT package can then be called to show the data that was read.
See Oracle Database SecureFiles and Large Objects Developer's Guide for additional code samples and descriptions of the access methods provided.
/* Checking if a pattern exists in a BFILE using instr
/* Procedure compareBFILEs_proc is not part of DBMS_LOB package: */
CREATE OR REPLACE PROCEDURE compareBFILEs_proc IS
/* Initialize the BFILE locator: */
file_loc1 BFILE := BFILENAME('MEDIA_DIR', 'keyboard.jpg');
file_loc2 BFILE;
Retval INTEGER;
BEGIN
DBMS_OUTPUT.PUT_LINE('------------ LOB COMPARE EXAMPLE ------------');
/* Select the LOB: */
SELECT ad_graphic INTO File_loc2 FROM print_media
WHERE Product_ID = 3060 AND ad_id = 11001;
/* Open the BFILEs: */
DBMS_LOB.OPEN(File_loc1, DBMS_LOB.LOB_READONLY);
DBMS_LOB.OPEN(File_loc2, DBMS_LOB.LOB_READONLY);
Retval := DBMS_LOB.COMPARE(File_loc2, File_loc1, DBMS_LOB.LOBMAXSIZE, 1, 1);
/* Close the BFILEs: */
DBMS_LOB.CLOSE(File_loc1);
DBMS_LOB.CLOSE(File_loc2);
END;
/
The approach shown in this example mimics that of the COMPARE example shown earlier. Because we are working with BFILEs, there are two additional sections: the DBMS_LOB.OPEN calls to open the files and the DBMS_LOB.CLOSE calls to close the files when the
COMPARE has completed.
Reading data from BFILEs follows the steps shown earlier for the READ function, with the addition of the calls to open and close the file. The
READ process is illustrated via the fread.sql demo file provided by Oracle in the/rdbms/demo/logs/plsql subdirectory:
/* This file is installed in the following path when you install */
/* the database: $ORACLE_HOME/rdbms/demo/lobs/plsql/fread.sql */
/* Reading data from a BFILE. */
/* Procedure readBFILE_proc is not part of DBMS_LOB package: */
CREATE OR REPLACE PROCEDURE readBFILE_proc IS
file_loc BFILE;
Amount INTEGER := 32767;
Position INTEGER := 1;
Buffer RAW(32767);
BEGIN
DBMS_OUTPUT.PUT_LINE('------------ BFILE READ EXAMPLE ------------');
/* Select the LOB: */
SELECT ad_graphic INTO File_loc FROM print_media
WHERE product_id = 3060 AND ad_id = 11001;
/* Open the BFILE: */
Reprinted for F2ZK5/193522, SAIC
Page 17 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited
Oracle Database 11g: The Complete Reference
DBMS_LOB.OPEN(File_loc, DBMS_LOB.LOB_READONLY);
/* Read data: */
DBMS_LOB.READ(File_loc, Amount, Position, Buffer);
/* Close the BFILE: */
DBMS_LOB.CLOSE(File_loc);
END;
/
If you use an Exception Handling section in your PL/SQL block, you need to be sure to include FILECLOSE procedure calls within the declared exceptions. (Refer to Chapter 32 for further details on exception handling within PL/SQL blocks.)
To move data from an external file into a BLOB datatype, you can create a BFILE datatype in a table and use the BFILENAME function to create a LOB locator that points to the external file. The BFILENAME function takes two parameters: the directory name and the filename.
Here's an example: insert into PROPOSAL (Proposal_ID, Cover_Letter) values (4, BFILENAME ('proposal_dir','extfile.doc'));
You can then open the file and use the LOADFROMFILE, LOADBLOBFROMFILE, or LOADCLOBFROMFILE procedure to load the BLOB datatype with the data from the external file.
If the data is presently in a LONG datatype, you can change it to a CLOB or NCLOB column via the alter table command. You can also use alter table to change a LONG RAW column to a BLOB datatype column. For insert as select operations, you can use the TO_LOB SQL function to move the data from the LONG column to a BLOB column.
When you delete LOB values, the locator value is deleted. If the deleted value is an internal LOB (BLOB, CLOB, or NCLOB), both the locator and the LOB value are deleted. If the deleted value is an external LOB (BFILE), only the locator value is deleted; you will need to manually delete the file to which the locator points.
Reprinted for F2ZK5/193522, SAIC
Page 18 / 18
Oracle Press, The McGrawHill Companies, Inc. (c) 2009, Copying Prohibited