Как получить текстовое содержимое из blob в oracle sql

11 ответов

Лучший ответ

Прежде всего, вы можете захотеть хранить текст в столбцах CLOB / NCLOB вместо BLOB, который предназначен для двоичных данных (кстати, ваш запрос будет работать с CLOB).

Следующий запрос позволит вам увидеть первые 32767 символов (максимум) текста внутри большого двоичного объекта при условии, что все наборы символов совместимы (исходная CS текста, хранящегося в BLOB, CS базы данных, используемой для VARCHAR2):

148

Mac
19 Авг 2013 в 06:01

SQL Developer также предоставляет эту функциональность:

Дважды щелкните ячейку сетки результатов и щелкните изменить:

Затем в верхней правой части всплывающего окна «Просмотреть как текст» (вы даже можете видеть изображения ..)

Вот и все!

21

nullPointer
7 Дек 2018 в 15:12

Вы можете использовать приведенный ниже SQL для чтения полей BLOB из таблицы.

16

Hemang
23 Дек 2014 в 11:12

Если вы хотите искать внутри текста, а не просматривать его, это работает:

7

Barn
18 Фев 2014 в 17:13

Ответ Barn сработал для меня с модификацией, потому что мой столбец не сжат. Быстрое и грязное решение:

3

Pecos Bill
11 Апр 2014 в 17:13

Некоторое время я боролся с этим и реализовал решение PL / SQL, но позже понял, что в Toad вы можете просто дважды щелкнуть ячейку сетки результатов, и появится редактор с текстовым содержимым. (я использую Toad v11)

3

Sonic Soul
13 Май 2014 в 13:06

Используйте этот SQL, чтобы получить первые 2000 символов большого двоичного объекта.

Примечание. Это связано с тем, что Oracle не сможет обработать преобразование BLOB, длина которого превышает 2000.

2

Swapnil Ingle
15 Янв 2020 в 14:25

Вы можете попробовать это:

Однако он будет ограничен 4000 байтами

1

Reza Rahimi
13 Июл 2018 в 19:49

Если ваш текст сжат внутри большого двоичного объекта с использованием алгоритма DEFLATE, и он довольно большой, вы можете использовать эту функцию для его чтения.

Затем запустите select, чтобы получить текст

Надеюсь, это кому-то поможет.

1

Arsen Salamakha
14 Мар 2019 в 15:12

Работал у меня,

-2

Narendra Kalekar
16 Ноя 2018 в 06:13

Используйте функцию .

Преобразует данные , , или в набор символов базы данных. Возвращаемое значение всегда .

-4

Michael Dillon
17 Июн 2012 в 14:45

LOB Locators and BFILE Locators

There are differences between the semantics of locators for LOB types , , and on one hand, and the semantics of locators for the type on the other hand:

  • For LOB types , , and , the LOB column stores a locator to the LOB value. Each LOB instance has its own distinct LOB locator and also a distinct copy of the LOB value.

  • For initialized columns, the row stores a locator to the external operating system file that holds the value of the . Each instance in a given row has its own distinct locator; however, two different rows can contain a locator that points to the same operating system file.

Regardless of where the value of a LOB is stored, a locator is stored in the table row of any initialized LOB column. Note that when the term locator is used without an identifying prefix term, it refers to both LOB locators and locators. Also, when you select a LOB from a table, the LOB returned is always a temporary LOB. For more information on working with locators for temporary LOBs, see .

Table print_media

The table of the Oracle Database Sample Schema , is used in many examples in this documentation and is defined as:

CREATE TABLE print_media
    ( product_id        NUMBER(6)
    , ad_id             NUMBER(6)
    , ad_composite      BLOB
    , ad_sourcetext     CLOB
    , ad_finaltext      CLOB
    , ad_fltextn        NCLOB
    , ad_textdocs_ntab  textdoc_tab
    , ad_photo          BLOB
    , ad_graphic        BFILE
    , ad_header         adheader_typ
    ) NESTED TABLE ad_textdocs_ntab STORE AS textdocs_nestedtab;

See Also:

for the details of how and its associated tables and files are created.

Opening and Closing LOBs

The LOB APIs include operations that enable you to explicitly open and close a LOB instance. You can open and close a persistent LOB instance of any type: , , , or . You open a LOB to achieve one or both of the following results:

  • Open the LOB in read-only mode.

    This ensures that the LOB (both the LOB locator and LOB value) cannot be changed in your session until you explicitly close the LOB. For example, you can open the LOB to ensure that the LOB is not changed by some other part of your program while you are using the LOB in a critical operation. After you perform the operation, you can then close the LOB.

  • Open the LOB in read write/mode—persistent , , or instances only.

    Opening a LOB in read write mode defers any index maintenance on the LOB column until you close the LOB. Opening a LOB in read write mode is only useful if there is an extensible index on the LOB column and you do not want the database to perform index maintenance every time you write to the LOB. This technique can increase the performance of your application if you are doing several write operations on the LOB while it is open.

If you open a LOB, then you must close the LOB at some point later in your session. This is the only requirement for an open LOB. While a LOB instance is open, you can perform as many operations as you want on the LOB—provided the operations are allowed in the given mode.

LOB Rules and Restrictions

This section provides details on LOB rules and restrictions.

Rules for LOB Columns

LOB columns are subject to the following rules and restrictions:

  • You cannot specify a LOB as a primary key column.

  • Oracle Database has limited support for remote LOBs. You can perform and / of LOB columns.

    For example:

    CREATE TABLE t AS SELECT * FROM table1@remote_site;
    INSERT INTO t SELECT * FROM table1@remote_site;
    UPDATE t SET lobcol = (SELECT lobcol FROM table1@remote_site);
    INSERT INTO table1@remote_site SELECT * from local_table;
    UPDATE table1@remote_site SET lobcol = (SELECT lobcol FROM local_table);
    DELETE FROM table1@remote_site <WHERE clause involving non_lob_columns>
    
    

    In statements structured like the preceding examples, only standalone LOB columns are allowed in the select list.

    SQL functions and APIs are not supported for use with remote LOB columns. For example, the following statement is supported:

    CREATE TABLE AS SELECT clob_col FROM tab@dbs2; 
    
    

    However, the following statement is not supported:

    CREATE TABLE AS SELECT DBMS_LOB.SUBSTR(clob_col) from tab@dbs2; 
    
    

    In addition, you can insert a character or binary buffer into a remote or , and select a remote or into a character or binary buffer. For example (in PL/SQL):

    SELECT clobcol1, type1.blobattr INTO varchar_buf1, raw_buf2 FROM
       table1@remote_site;
    INSERT INTO table1@remotesite (clobcol1, type1.blobattr) VALUES varchar_buf1,
       raw_buf2;
    
    

    This is the only supported syntax involving LOBs in remote tables. No other usage is supported.

  • Clusters cannot contain LOBs, either as key or nonkey columns.

  • The following data structures are supported only as temporary instances. You cannot store these instances in database tables:

    • of any LOB type

    • of any type containing a LOB type, such as an object type with a LOB attribute

    • of any LOB type

    • of any type containing a LOB

  • You cannot specify LOB columns in the clause of a query, or in the clause of a query or in an aggregate function.

  • You cannot specify a LOB column in a … or … statement or in a join. However, you can specify a LOB attribute of an object type column in a … statement or in a query that uses the or set operator if the column’s object type has a or function defined on it.

  • You cannot specify LOB columns in … or … statements.

  • The first () extent of a LOB segment must contain at least three database blocks.

  • When creating an DML trigger, you cannot specify a LOB column in the clause.

  • You cannot specify a LOB column as part of an index key. However, you can specify a LOB column in the indextype specification of a domain index. In addition, Oracle Text lets you define an index on a column.

  • In an … operation, you can bind up to 4000 bytes of data to LOB columns and attributes.

  • If a table has both and LOB columns, you cannot bind more than 4000 bytes of data to both the and LOB columns in the same SQL statement. However, you can bind more than 4000 bytes of data to either the or the LOB column.

Note:

For a table on which you have defined a DML trigger, if you use OCI functions or package to change the value of a LOB column or the LOB attribute of an object type column, the database does not fire the DML trigger.

See Also:

  • under , describes LONG to LOB migration limitations for clustered tables, replication, triggers, domain indexes, and function-based indexes.

  • for restrictions on SQL semantics.

  • For details on the INITIAL extent of a LOB segment, see .

  • LOBs in partitioned index-organized tables are also subject to a number of other restrictions. See for more information.

Restrictions for LOB Operations

Other general LOB restrictions include the following:

  • In SQL Loader, A field read from a LOBFILE cannot be used as an argument to a clause. See for more information.

  • Session migration is not supported for s in shared server (multithreaded server) mode. This implies that operations on open s can persist beyond the end of a call to a shared server. In shared server sessions, operations will be bound to one shared server, they cannot migrate from one server to another.

Accessing LOBs

You can access a LOB instance using the following techniques:

Accessing a LOB Using SQL

Support for columns that use LOB datatypes is built into many SQL functions. This support enables you to use SQL semantics to access LOB columns in SQL. In most cases, you can use the same SQL semantics on a LOB column that you would use on a column.

See Also:

For details on SQL semantics support for LOBs, see .

Accessing a LOB Using the Data Interface

You can select a LOB directly into or buffers using the LONG-to-LOB API in OCI and PL/SQL. In the following PL/SQL example, is selected into a buffer .

DECLARE
    final_ad VARCHAR(32767);
BEGIN
    SELECT ad_finaltext INTO final_ad FROM print_media
        WHERE product_id = 2056 and ad_id = 12001 ; 
    /* PUT_LINE can only output up to 255 characters at a time  */
    ...
    DBMS_OUTPUT.PUT_LINE(final_ad);
    /* more calls to read final_ad */
    ...
END;

See Also:

For more details on accessing LOBs using the data interface, see .

LOB Locator and LOB Value

There are two techniques that you can use to access and modify LOB values:

Using the Data Interface for LOBs

You can perform bind and define operations on and columns in C applications using the data interface for LOBs in OCI. Doing so, enables you to insert or select out data in a LOB column without using a LOB locator as follows:

  • Using a bind variable associated with a LOB column to insert character data into a , or data into a .

  • Using a define operation to define an output buffer in your application that will hold character data selected from a , or data selected from a .

    See Also:

    for more information on implicit assignment of LOBs to other datatypes.

BLOB в Oracle преобразуется в Clob

http-equiv=»Content-Type» content=»text/html;charset=UTF-8″>yle=»margin-bottom:5px;»>Теги:  Oracle  Blob  Clob  Преобразование типа данных

Если поле C_XML в таблице вкладки изначально является типом BLOB, мы должны преобразовать его в тип Clob. Если есть данные в таблице, она не может быть изменена непосредственно через оператор оповещения. По следующему способу вы можете изменить поле типа BLOB в тип CLOB.

Сначала создайте функцию в Oracle, код выглядит следующим образом:

Затем создайте резервный стол для предотвращения потери данных. Кодовое шоу, как показано ниже:

Снимите столбец BLOB в таблице и добавьте колонку Clob. Кодовое шоу, как показано ниже:

Наконец, резервные данные будут восстановлены обратно. Кодовое шоу, как показано ниже:

Интеллектуальная рекомендация

19.03.21 Я загрузил комплексные обучающие видеоуроки Photoshop CC 2015 и обучающие видеоуроки по новым функциям PS CC 2015. Я просмотрел несколько видео, но мне кажется, что они в основном объясняют н…

проверка данных весеннего mvc Два способа проверки данных Spring MVC: 1.JSR303 2.Hibernate Validator Второй метод является дополнением к первому методу Шаги для проверки данных с использованием Hibern…

Существует два способа вызова между сервисами Springcloud: RestTemplate и Feign. Здесь мы представляем сервисы вызова RestTemplate. 1. Что такое RestTemplate RestTemplate — это структура веб-запросов …

1. Понимать предварительный, средний, последующий порядок и иерархическую последовательность бинарных деревьев; Свяжите язык C со структурой данных двоичного дерева; Освойте с…

Вам также может понравиться

Последнее обучение, как использовать Kaldi, чтобы проснуться без использования WSTF, поэтому вам нужно глубоко пойти в Kaldi для обучения. Временное состояние обучения. Три изображения представляют со…

Во время простоя некоторые веб-страницы, которые мы создали, не были завершены, но не хотят, чтобы другие видели, вы можете создать простой эффект шифрования страницы на странице этой веб-страницы, ан…

Расширенные статьи серии Zookeeper 1. NIO, ZAB соглашение, 2PC представления концепции 2. Лидер выборов 3. Рукописный распределенный замок, центр настройки ==================================== 1. NIO,…

Посмотрите на конечный эффект первым DemoPreview.gif SETP1 эффект капли воды Первая реакция на эффект капли воды — нарисовать замкнутую кривую. С помощью события MotionEvent измените радиус во время п…

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Все про сервера
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: