SQL Pl-SQL Concepts

Embed Size (px)

Citation preview

  • 8/3/2019 SQL Pl-SQL Concepts

    1/23

    SQL/PL-SQL Concepts:

    Global Temporary Tables:

    Applications often use some form of temporary data store for processes that are

    to complicated to complete in a single pass. Often, these temporary stores aredefined as database tables or PL/SQL tables. In Oracle 8i, the maintenance andmanagement of temporary tables can be delegated to the server by using GlobalTemporary Tables.

    Creation of Temporary Global Tables

    Miscellaneous Features

    Creation of Global Temporary Tables:

    The data in a global temporary table is private, such that data inserted by a

    session can only be accessed by that session. The session-specific rows in aglobal temporary table can be preserved for the whole session, or just for thecurrent transaction. The ON COMMIT DELETE ROWS clause indicates that thedata should be deleted at the end of the transaction.

    CREATE GLOBAL TEMPORARY TABLE my_temp_table (column1 NUMBER,column2 NUMBER

    ) ON COMMIT DELETE ROWS;

    In contrast, the ON COMMIT PRESERVE ROWS clause indicates that rows

    should be preserved until the end of the session.

    CREATE GLOBAL TEMPORARY TABLE my_temp_table (column1 NUMBER,column2 NUMBER

    ) ON COMMIT PRESERVE ROWS;

    Miscellaneous Features:

    If the TRUNCATE statement is issued against a temporary table, only thesession specific data is trucated. There is no affect on the data of other

    sessions. Data in temporary tables is automatically delete at the end of the database

    session, even if it ends abnormally.

    Indexes can be created on temporary tables. The content of the index andthe scope of the index is that same as the database session.

    Views can be created against temporary tables and combinations oftemporary and permanent tables.

    Temporary tables can have triggers associated with them.

    http://www.oracle-base.com/articles/8i/TemporaryTables.php#creation%23creationhttp://www.oracle-base.com/articles/8i/TemporaryTables.php#miscellaneous%23miscellaneoushttp://www.oracle-base.com/articles/8i/TemporaryTables.php#miscellaneous%23miscellaneoushttp://www.oracle-base.com/articles/8i/TemporaryTables.php#creation%23creation
  • 8/3/2019 SQL Pl-SQL Concepts

    2/23

    Export and Import utilities can be used to transfer the table definitions, butno data rows are processed.

    There are a number of restrictions related to temporary tables but theseare version specific.

    For more information on Global Temporary Tables please refer:

    Simple n Small:http://www.oracle-base.com/articles/8i/TemporaryTables.php#creation

    In Depth:http://www.indiana.edu/~dss/Services/DataWarehouse/Oracle/TemporaryTables/tmptab.html

    Definer rights:

    A routine stored in the database by default, is executed with the definer rights(owner of the routine), depending on the user who calls it. This is a good way ofhaving the required code perform process logic in one place. It gives bettercontrol, preventing direct access to objects that belong to another user, whichmight result in security issues.

    For example, table APPPARMST belongs to schema A. User A creates aprocedure UPDATE_PAR allowing for updates of a table. User B is grantedexecute privileges on the procedure. Now user B cannot access the table as no

    privileges have been granted, but can call the procedure to do the requiredprocess logic for updating the table.

    Invoker Rights:

    Invoker rights is a new model for resolving references to database elements in aPL/SQL program unit. From Oracle 8i onwards, we can decide if a program unitshould run with the authority of the definer or of the invoker. This means thatmultiple schemas, accessing only those elements belonging to the invoker, canshare the same piece of code.

    For example, let's take the above case. The table, APPPARMST, is created inschema B also. Each of the schema will now own the same set of objects butdifferent data, as they are being used for different purposes. Since the calledprocedure, UPDATE_PAR, is owned by User A, the ideal solution in Oracle 8and earlier releases, was to compile it in schema B also, so that it will use theobjects thereof.

  • 8/3/2019 SQL Pl-SQL Concepts

    3/23

    With Oracle 8i, there is no need for this duplication of code. A single compiledprogram unit can be made to use schema A's objects when invoked by User Aand schema B's objects when invoked by User B. This way, we have the optionof creating a code repository in one place and sharing it with various productionusers.The owner of the routine must grant EXECUTE privilege to other users.

    To enable code to run with Invoker rights, an AUTHID clause needs to be usedbefore the IS or AS keyword in the routine header. The AUTHID clause tellsOracle whether the routine is to be run with the invoker rights(CURRENT_USER), or with the Owner rights (DEFINER). If you do not specifythis clause, Oracle by default assumes it to be AUTHID DEFINER .

    E.g.

    Conn to apps user

    Create or replace procedure XXX_TEST_PRCAUTHID CURRENT_USERisv_name varchar2(10);

    BEGINselect nameinto v_namefrom XXX_TESTwhere rownum

  • 8/3/2019 SQL Pl-SQL Concepts

    4/23

    For more information please refer:http://www.databasejournal.com/features/oracle/article.php/1574831/Definer-and-Invoker-Rights-for-stored-routines-in-Oracle.htm

    Forward Reference and Mutual Recursion Rare and imp feature of pl/sql

    Two Oracle PL/SQL Features You Probably Dont Know About

    Oracle PL/SQL has a neat and little known feature called forward declaration. Inthis post Im going to do a quick review of what forward declaration is, how it can

    be used and a situation in which forward declarations are absolutely required,mutual recursion.

    As you already know, PL/SQL requires that you declare elements (variables,procedures and functions) before using them in your code.

    For example:

    SQL> CREATE OR REPLACE PACKAGE my_pkg2 IS3 FUNCTION my_func4 RETURN NUMBER;

    5 END my_pkg;6 /

    Package created.

    SQL> CREATE OR REPLACE PACKAGE BODY my_pkg2 AS3 FUNCTION my_func

    http://www.databasejournal.com/features/oracle/article.php/1574831/Definer-and-Invoker-Rights-for-stored-routines-in-Oracle.htmhttp://www.databasejournal.com/features/oracle/article.php/1574831/Definer-and-Invoker-Rights-for-stored-routines-in-Oracle.htmhttp://www.databasejournal.com/features/oracle/article.php/1574831/Definer-and-Invoker-Rights-for-stored-routines-in-Oracle.htmhttp://www.databasejournal.com/features/oracle/article.php/1574831/Definer-and-Invoker-Rights-for-stored-routines-in-Oracle.htm
  • 8/3/2019 SQL Pl-SQL Concepts

    5/23

    4 RETURN NUMBER5 IS6 BEGIN7 RETURN my_func2;8 END my_func;

    910 FUNCTION my_func211 RETURN NUMBER12 IS13 BEGIN14 RETURN 0;15 END my_func2;16 END my_pkg;17 /

    Warning: Package Body created with compilation errors.

    SQL> show errorsErrors for PACKAGE BODY MY_PKG:

    LINE/COL ERROR-------- ------------------------------------------------7/7 PL/SQL: Statement ignored7/14 PLS-00313: 'MY_FUNC2' not declared in this scope

    The reason the compilation of my_pkg failed is because my_func calls my_func2,which is not yet declared when the call is made. To correct this error, you have

    three options. The first option is to create my_func2 (header and body) beforemy_func in the package body. The second option is to declare my_func2 in thepackage specification. The third option is to use a forward declaration ofmy_func2 in the package body.

    Forward Declarations:

    A forward declaration means that modules (procedures and functions) aredeclared in advance of their actual body definition. This declaration makes thatmodule available to be called by other modules even before the programs bodyis defined. A forward declaration consists simply of the module header, which is

    just the name of the module followed by the parameter list (and a RETURNclause in case the module is a function), no more no less.

    For example:

    SQL> CREATE OR REPLACE PACKAGE BODY my_pkg2 AS3 FUNCTION my_func24 RETURN NUMBER; -- forward declaration

  • 8/3/2019 SQL Pl-SQL Concepts

    6/23

    56 FUNCTION my_func7 RETURN NUMBER8 IS9 BEGIN

    10 RETURN my_func2; -- Legal call11 END my_func;1213 FUNCTION my_func214 RETURN NUMBER15 IS16 BEGIN17 RETURN 0;18 END my_func2;19 END my_pkg;20 /

    Package body created.

    Its worth noting that the definition for a forwardly declared program must becontained in the declaration section of the same PL/SQL block (anonymousblock, procedure, function, or package body) in which you code the forwarddeclaration.

    Mutually Recursive Routines:Now you ask: Whats the use of forward declarations? In most cases, forwarddeclarations are not needed. However, forward declarations are required in one

    specific situation: mutual recursion. In fact, without PL/SQLs forward declarationfeature, it is not possible to have mutual recursion, in which two or moreprograms directly or indirectly call each other.

    Here is an example of mutual recursion and forward declaration in action. TheBoolean functions odd and even, which determine whether a number is odd oreven, call each other directly. The forward declaration of odd is necessarybecause even calls odd, which is not yet declared when the call is made.

    SQL> CREATE OR REPLACE PACKAGE my_pkg

    2 IS3 FUNCTION odd_or_even (n NATURAL)4 RETURN VARCHAR2;5 END my_pkg;6 /

  • 8/3/2019 SQL Pl-SQL Concepts

    7/23

    Package created.

    SQL> CREATE OR REPLACE PACKAGE BODY my_pkg2 AS3 FUNCTION odd_or_even (n NATURAL)

    4 RETURN VARCHAR25 IS6 l_return_var VARCHAR2 (4);78 FUNCTION odd (n NATURAL)9 RETURN BOOLEAN; -- forward declaration

    1011 FUNCTION even (n NATURAL)12 RETURN BOOLEAN13 IS14 BEGIN

    15 IF n = 016 THEN17 RETURN TRUE;18 ELSE19 RETURN odd (n - 1); -- mutually recursive call20 END IF;21 END even;2223 FUNCTION odd (n NATURAL)24 RETURN BOOLEAN25 IS

    26 BEGIN27 IF n = 028 THEN29 RETURN FALSE;30 ELSE31 RETURN even (n - 1); -- mutually recursive call32 END IF;33 END odd;34 BEGIN35 IF even (n)36 THEN37 l_return_var := 'even';38 ELSIF odd (n)39 THEN40 l_return_var := 'odd';41 ELSE42 l_return_var := 'oops';43 END IF;44

  • 8/3/2019 SQL Pl-SQL Concepts

    8/23

    45 RETURN l_return_var;46 END odd_or_even;47 END my_pkg;48 /

    Package body created.

    SQL> SELECT my_pkg.odd_or_even (5) AS odd_or_even2 FROM DUAL

    3 /

    ODD_OR_EVEN

    ---------------------------------------------------------------------

    odd

    SQL> SELECT my_pkg.odd_or_even (6) AS odd_or_even

    2 FROM DUAL3 /

    ODD_OR_EVEN

    ---------------------------------------------------------------------even

    =====================================================

    That was a quick and hopefully useful refresher about two little known and rarely used

    features of the PL/SQL language: forward declarations and mutual recursion.

    Note: The example above is a modified version of the one in the

    http://download-

    west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/08_subs.htm#1178

    For more information on Forward Declaration please refer the below link:

    http://awads.net/wp/2007/04/30/two-oracle-plsql-features-you-probably-don

    %E2%80%99t-know-about/

    http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/08_subs.htm#1178http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/08_subs.htm#1178http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/08_subs.htm#1178http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/08_subs.htm#1178http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/08_subs.htm#1178
  • 8/3/2019 SQL Pl-SQL Concepts

    9/23

    SQL*Loader:

    What is SQL*Loader and what is it used for?

    SQL*Loader is a bulk loader utility used for moving data from external files into the

    Oracle database. Its syntax is similar to that of the DB2 load utility, but comes with moreoptions. SQL*Loader supports various load formats, selective loading, and multi-table

    loads.

    SQL*Loader (sqlldr) is the utility to use for high performance data loads. The data can be

    loaded from any text file and inserted into the database.

    How does one use the SQL*Loader utility?

    One can load data into an Oracle database by using the sqlldr (sqlload on some platforms)

    utility. Invoke the utility without arguments to get a list of available parameters. Look at

    the following example:

    sqlldr username@server/password control=loader.ctl

    sqlldr username/password@server control=loader.ctl

    This sample control file (loader.ctl) will load an external data file containing delimited

    data:

    load data

    infile 'c:\data\mydata.csv'

    into table emp

    fields terminated by "," optionally enclosed by '"'

    ( empno, empname, sal, deptno )

    The mydata.csv file may look like this:

    10001,"Scott Tiger", 1000, 40

    10002,"Frank Naude", 500, 20

    Optionally, you can work with tabulation delimited files by using one of the following

    syntaxes:

  • 8/3/2019 SQL Pl-SQL Concepts

    10/23

    fields terminated by "\t"

    fields terminated by X'09'

    Additionally, if your file was in Unicode, you could make the following addition.

    load data

    CHARACTERSET UTF16

    infile 'c:\data\mydata.csv'

    into table emp

    fields terminated by "," optionally enclosed by '"'

    ( empno, empname, sal, deptno )

    Another Sample control file with in-line data formatted as fix length records. The trick is

    to specify "*" as the name of the data file, and use BEGINDATA to start the data sectionin the control file:

    load data

    infile *

    replace

    into table departments

    ( dept position (02:05) char(4),

    deptname position (08:27) char(20)

    )

    begindata

    COSC COMPUTER SCIENCE

    ENGL ENGLISH LITERATURE

    MATH MATHEMATICS

    POLY POLITICAL SCIENCE

  • 8/3/2019 SQL Pl-SQL Concepts

    11/23

    How does one load MS-Excel data into Oracle?

    Open the MS-Excel spreadsheet and save it as a CSV (Comma Separated Values) file.

    This file can now be copied to the Oracle machine and loaded using the SQL*Loaderutility.

    Possible problems and workarounds:

    The spreadsheet may contain cells with newline characters (ALT+ENTER). SQL*Loader

    expects the entire record to be on a single line. Run the following macro to remove

    newline characters (Tools -> Macro -> Visual Basic Editor):

    ' Removing tabs and carriage returns from worksheet cells

    Sub CleanUp()

    Dim TheCell As Range

    On Error Resume Next

    For Each TheCell In ActiveSheet.UsedRange

    With TheCell

    If .HasFormula = False Then

    .Value = Application.WorksheetFunction.Clean(.Value)

    End If

    End With

    Next TheCell

    End Sub

    Tools:

    If you need a utility to load Excel data into Oracle, download quickload from sourceforgeat http://sourceforge.net/projects/quickload

    Is there a SQL*Unloader to download data to a flat file?

    Oracle does not supply any data unload utilities. Here are some workarounds:

  • 8/3/2019 SQL Pl-SQL Concepts

    12/23

    Using SQL*Plus

    You can use SQL*Plus to select and format your data and then spool it to a file. This

    example spools out a CSV (comma separated values) file that can be imported into MS-Excel:

    set echo off newpage 0 space 0 pagesize 0 feed off head off trimspool on

    spool oradata.txt

    select col1 || ',' || col2 || ',' || col3from tab1

    where col2 = 'XYZ';

    spool off

    You can also use the "set colsep" command if you don't want to put the commas in byhand. This saves a lot of typing. Example:

    set colsep ','set echo off newpage 0 space 0 pagesize 0 feed off head off trimspool on

    spool oradata.txtselect col1, col2, col3

    from tab1

    where col2 = 'XYZ';spool off

    Using PL/SQL

    PL/SQL's UTL_FILE package can also be used to unload data. Example:

    declare

    fp utl_file.file_type;begin

    fp := utl_file.fopen('c:\oradata','tab1.txt','w');

    utl_file.putf(fp, '%s, %sn', 'TextField', 55);

    utl_file.fclose(fp);end;

    /

    Third-party programs

    You might also want to investigate third party tools to help you unload data from Oracle.

    Here are some examples:

    WisdomForce FastReader - http://www.wisdomforce.com

    IxUnload from ixionsoftware.com - http://www.ixionsoftware.com/products/

    FAst extraCT (FACT) for Oracle from CoSort - http://www.cosort.com/products/FACT

  • 8/3/2019 SQL Pl-SQL Concepts

    13/23

    Unicenter (also ManageIT or Platinum) Fast Unload for Oracle from CA

    Keeptool's Hora unload/load facility (part v5 to v6 upgrade) can export to formats such as

    Microsoft Excel, DBF, XML, and text.

    TOAD from QuestSQLWays from Ispirer Systems

    PL/SQL Developer from allroundautomation

    Can one load variable and fixed length data records?

    Loading delimited (variable length) data

    In the first example we will show how delimited (variable length) data can be loaded into

    Oracle:

    LOAD DATAINFILE *

    INTO TABLE load_delimited_data

    FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'

    TRAILING NULLCOLS( data1,

    data2

    )

    BEGINDATA

    11111,AAAAAAAAAA

    22222,"A,B,C,D,"

    NOTE: The default data type in SQL*Loader is CHAR(255). To load character fieldslonger than 255 characters, code the type and length in your control file. By doing this,

    Oracle will allocate a big enough buffer to hold the entire column, thus eliminating

    potential "Field in data file exceeds maximum length" errors. Example:

    ...resume char(4000),

    ...

    Loading positional (fixed length) data

    If you need to load positional data (fixed length), look at the following control fileexample:

    LOAD DATA

    INFILE *

    INTO TABLE load_positional_data

  • 8/3/2019 SQL Pl-SQL Concepts

    14/23

    ( data1 POSITION(1:5),

    data2 POSITION(6:15)

    )

    BEGINDATA

    11111AAAAAAAAAA

    22222BBBBBBBBBB

    For example, position(01:05) will give the 1st to the 5th character (11111 and 22222).

    [edit] Can one skip header records while loading?

    One can skip unwanted header records or continue an interrupted load (for example if

    you run out of space) by specifying the "SKIP=n" keyword. "n" specifies the number oflogical rows to skip. Look at these examples:

    OPTIONS (SKIP=5)

    LOAD DATA

    INFILE *

    INTO TABLE load_positional_data

    ( data1 POSITION(1:5),

    data2 POSITION(6:15)

    )

    BEGINDATA

    11111AAAAAAAAAA

    22222BBBBBBBBBB

    ...sqlldr userid=ora_id/ora_passwd control=control_file_name.ctl skip=4

  • 8/3/2019 SQL Pl-SQL Concepts

    15/23

    If you are continuing a multiple table direct path load, you may need to use the

    CONTINUE_LOAD clause instead of the SKIP parameter. CONTINUE_LOAD allows

    you to specify a different number of rows to skip for each of the tables you are loading.

    Can one modify data as the database gets loaded?

    Data can be modified as it loads into the Oracle Database. One can also populate columns

    with static or derived values. However, this only applies for the conventional load path

    (and not for direct path loads). Here are some examples:

    LOAD DATAINFILE *

    INTO TABLE modified_data

    ( rec_no "my_db_sequence.nextval",region CONSTANT '31',

    time_loaded "to_char(SYSDATE, 'HH24:MI')",

    data1 POSITION(1:5) ":data1/100",data2 POSITION(6:15) "upper(:data2)",

    data3 POSITION(16:22)"to_date(:data3, 'YYMMDD')"

    )

    BEGINDATA

    11111AAAAAAAAAA991201

    22222BBBBBBBBBB990112

    LOAD DATA

    INFILE 'mail_orders.txt'BADFILE 'bad_orders.txt'

    APPENDINTO TABLE mailing_listFIELDS TERMINATED BY ","

    ( addr,

    city,state,

    zipcode,

    mailing_addr "decode(:mailing_addr, null, :addr, :mailing_addr)",mailing_city "decode(:mailing_city, null, :city, :mailing_city)",

    mailing_state,

    move_date "substr(:move_date, 3, 2) || substr(:move_date, 7, 2)"

    )

    Can one load data from multiple files/ into multiple tables at once?

    Loading from multiple input files

  • 8/3/2019 SQL Pl-SQL Concepts

    16/23

    One can load from multiple input files provided they use the same record format by

    repeating the INFILE clause. Here is an example:

    LOAD DATAINFILE file1.dat

    INFILE file2.datINFILE file3.dat

    APPENDINTO TABLE emp

    ( empno POSITION(1:4) INTEGER EXTERNAL,

    ename POSITION(6:15) CHAR,deptno POSITION(17:18) CHAR,

    mgr POSITION(20:23) INTEGER EXTERNAL

    )Loading into multiple tables

    One can also specify multiple "INTO TABLE" clauses in the SQL*Loader control file toload into multiple tables. Look at the following example:

    LOAD DATA

    INFILE *

    INTO TABLE tab1 WHEN tab = 'tab1'

    ( tab FILLER CHAR(4),

    col1 INTEGER

    )

    INTO TABLE tab2 WHEN tab = 'tab2'

    ( tab FILLER POSITION(1:4),

    col1 INTEGER

    )

    BEGINDATA

    tab1|1

    tab1|2

  • 8/3/2019 SQL Pl-SQL Concepts

    17/23

    tab2|2

    tab3|3

    The "tab" field is marked as a FILLER as we don't want to load it.

    Note the use of "POSITION" on the second routing value (tab = 'tab2'). By default fieldscanning doesn't start over from the beginning of the record for new INTO TABLE

    clauses. Instead, scanning continues where it left off. POSITION is needed to reset the

    pointer to the beginning of the record again. In delimited formats, use "POSITION(1)"after the first column to reset the pointer.

    Another example:

    LOAD DATA

    INFILE 'mydata.dat'

    REPLACE

    INTO TABLE emp

    WHEN empno != ' '

    ( empno POSITION(1:4) INTEGER EXTERNAL,

    ename POSITION(6:15) CHAR,

    deptno POSITION(17:18) CHAR,

    mgr POSITION(20:23) INTEGER EXTERNAL

    )

    INTO TABLE proj

    WHEN projno != ' '

    ( projno POSITION(25:27) INTEGER EXTERNAL,

    empno POSITION(1:4) INTEGER EXTERNAL

    )

  • 8/3/2019 SQL Pl-SQL Concepts

    18/23

    Can one selectively load only the records that one needs?

    Look at this example, (01) is the first character, (30:37) are characters 30 to 37:

    LOAD DATA

    INFILE 'mydata.dat' BADFILE 'mydata.bad' DISCARDFILE 'mydata.dis'APPEND

    INTO TABLE my_selective_tableWHEN (01) 'H' and (01) 'T' and (30:37) = '20031217'

    (

    region CONSTANT '31',service_key POSITION(01:11) INTEGER EXTERNAL,

    call_b_no POSITION(12:29) CHAR

    )

    NOTE: SQL*Loader does not allow the use of OR in the WHEN clause. You can onlyuse AND as in the example above! To workaround this problem, code multiple "INTO

    TABLE ... WHEN" clauses. Here is an example:

    LOAD DATAINFILE 'mydata.dat' BADFILE 'mydata.bad' DISCARDFILE

    'mydata.dis'

    APPENDINTO TABLE my_selective_table

    WHEN (01) 'H' and (01) 'T'

    (

    region CONSTANT '31',service_key POSITION(01:11) INTEGER EXTERNAL,

    call_b_no POSITION(12:29) CHAR

    )INTO TABLE my_selective_table

    WHEN (30:37) = '20031217'

    (region CONSTANT '31',

    service_key POSITION(01:11) INTEGER EXTERNAL,

    call_b_no POSITION(12:29) CHAR)

    Can one skip certain columns while loading data?

    One cannot use POSITION(x:y) with delimited data. Luckily, from Oracle 8i one can

    specify FILLER columns. FILLER columns are used to skip columns/fields in the loadfile, ignoring fields that one does not want. Look at this example:

  • 8/3/2019 SQL Pl-SQL Concepts

    19/23

    LOAD DATA

    TRUNCATE INTO TABLE T1

    FIELDS TERMINATED BY ','( field1,

    field2 FILLER,

    field3)

    BOUNDFILLER (available with Oracle 9i and above) can be used if the skipped

    column's value will be required later again. Here is an example:

    LOAD DATA

    INFILE *TRUNCATE INTO TABLE sometable

    FIELDS TERMINATED BY "," trailing nullcols

    (

    c1,field2 BOUNDFILLER,

    field3 BOUNDFILLER,field4 BOUNDFILLER,

    field5 BOUNDFILLER,

    c2 ":field2 || :field3",c3 ":field4 + :field5"

    )

    How does one load multi-line records?

    One can create one logical record from multiple physical records using one of thefollowing two clauses:

    CONCATENATE - use when SQL*Loader should combine the same number of physical

    recordstogether to form one logical record.

    CONTINUEIF - use if a condition indicates that multiple records should be treated as

    one. Eg. by having a '#' character in column 1.

    How does one load records with multi-line fields?

    Using Stream Record format, you can define a record delimiter, so that you're allowed tohave the default delimiter ('\n') in the field's content.

    After the INFILE clause set the delimiter:

    load data

    infile "test.dat" "str '|\n'"into test_table

  • 8/3/2019 SQL Pl-SQL Concepts

    20/23

    fields terminated by ';' TRAILING NULLCOLS

    (

    desc,txt

    )

    test.dat:

    one line;hello dear world;|

    two lines;Dear world,

    hello!;|

    Note that this doesn't seem to work with inline data (INFILE * and BEGINDATA).

    How can one get SQL*Loader to COMMIT only at the end of the load file?

    One cannot, but by setting the ROWS= parameter to a large value, committing can bereduced. Make sure you have big rollback segments ready when you use a high value for

    ROWS=.

    Can one improve the performance of SQL*Loader?

    A very simple but easily overlooked hint is not to have any indexes and/or constraints

    (primary key) on your load tables during the load process. This will significantly slow

    down load times even with ROWS= set to a high value.

    Add the following option in the command line: DIRECT=TRUE. This will effectively

    bypass most of the RDBMS processing. However, there are cases when you can't usedirect load. For details, refer to the FAQ about the differences between the conventional

    and direct path loader below.

    Turn off database logging by specifying the UNRECOVERABLE option. This option canonly be used with direct data loads.

    Run multiple load jobs concurrently.

    [edit] What is the difference between the conventional and direct path loader?

    The conventional path loader essentially loads the data by using standard INSERTstatements. The direct path loader (DIRECT=TRUE) bypasses much of the logicinvolved with that, and loads directly into the Oracle data files. More information about

    the restrictions of direct path loading can be obtained from the Oracle Server Utilities

    Guide (see chapter 8).

  • 8/3/2019 SQL Pl-SQL Concepts

    21/23

    Some of the restrictions with direct path loads are:

    Loaded data will not be replicated

    Cannot always use SQL strings for column processing in the control file (something like

    this will probably fail: col1 date "ddmonyyyy" "substr(:period,1,9)"). Details are inMetalink Note:230120.1.

    [edit] How does one use SQL*Loader to load images, sound clips and documents?

    SQL*Loader can load data from a "primary data file", SDF (Secondary Data file - for

    loading nested tables and VARRAYs) or LOBFILE. The LOBFILE method provides aneasy way to load documents, photos, images and audio clips into BLOB and CLOB

    columns. Look at this example:

    Given the following table:

    CREATE TABLE image_table (

    image_id NUMBER(5),file_name VARCHAR2(30),

    image_data BLOB);

    Control File:

    LOAD DATA

    INFILE *

    INTO TABLE image_table

    REPLACEFIELDS TERMINATED BY ','

    (image_id INTEGER(5),

    file_name CHAR(30),

    image_data LOBFILE (file_name) TERMINATED BY EOF

    )BEGINDATA

    001,image1.gif

    002,image2.jpg003,image3.jpg

    How does one load EBCDIC data?

    Specify the character set WE8EBCDIC500 for the EBCDIC data. The following exampleshows the SQL*Loader controlfile to load a fixed length EBCDIC record into the Oracle

    Database:

  • 8/3/2019 SQL Pl-SQL Concepts

    22/23

    LOAD DATA

    CHARACTERSET WE8EBCDIC500

    INFILE data.ebc "fix 86 buffers 1024"BADFILE data.bad'

    DISCARDFILE data.dsc'

    REPLACEINTO TABLE temp_data

    (

    field1 POSITION (1:4) INTEGER EXTERNAL,field2 POSITION (5:6) INTEGER EXTERNAL,

    field3 POSITION (7:12) INTEGER EXTERNAL,

    field4 POSITION (13:42) CHAR,

    field5 POSITION (43:72) CHAR,field6 POSITION (73:73) INTEGER EXTERNAL,

    field7 POSITION (74:74) INTEGER EXTERNAL,

    field8 POSITION (75:75) INTEGER EXTERNAL,

    field9 POSITION (76:86) INTEGER EXTERNAL

    For more information on SQL*Loader Concepts please refer the below link

    http://www.orafaq.com/wiki/SQL*Loader_FAQ

  • 8/3/2019 SQL Pl-SQL Concepts

    23/23