Category: Allgemein

  • Oracle package

    This programme contains a package along with a calling programma that uses this package. Let me first provide the package itself.

    The code:

    CREATE OR REPLACE PACKAGE employee_data 
    AS
      TYPE employee_cv_type IS REF CURSOR RETURN employee%ROWTYPE; 
      PROCEDURE open_employee_data (
               employee_cv   IN OUT employee_cv_type,
               x_dno         IN     employee.dno%TYPE);  
      PROCEDURE fetch_employee_data (
               employee_cv      IN    employee_cv_type,
               employee_output  OUT   VARCHAR2); 
     END employee_data;
     / 
    
     CREATE OR REPLACE PACKAGE BODY employee_data 
     AS 
     PROCEDURE open_employee_data (
         employee_cv   IN OUT employee_cv_type,
         x_dno         IN     employee.dno%TYPE) 
       IS
       BEGIN 
       OPEN employee_cv FOR
          SELECT *
          FROM employee
          WHERE employee.dno = x_dno;
     END open_employee_data; 
     PROCEDURE fetch_employee_data (
         employee_cv      IN    employee_cv_type,
         employee_output  OUT   VARCHAR2) 
       IS 
    employee_row  employee%ROWTYPE;
     BEGIN 
      FETCH employee_cv INTO employee_row;
      employee_output := employee_row.lname || ' ' || employee_row.salary;
     END fetch_employee_data; 
     END employee_data; 

    The calling programme looks like:

    DECLARE
       department_number  employee.dno%TYPE := 5;
       employee_cv        employee_data.employee_cv_type;
       employee_output    VARCHAR2(1000); 
    BEGIN
      employee_data.open_employee_data (employee_cv, department_number);
      LOOP 
       employee_data.fetch_employee_data (employee_cv, employee_output);
        EXIT WHEN employee_cv%NOTFOUND;
        dbms_output.put_line (employee_output); 
      END LOOP; 
    END;

  • Generate code in Oracle

    The idea is as follows. We want to create a simple function that calculates a code from a string. This code is the total ASCII value of the characters in a string. I used this code to act as a foreign key to which other tables may refer to.

    I use an Oracle function that is written as:

    create or replace
    function sumascii (str in varchar2) return number is
    x number := 0;
    begin
    for i in 1..length (str)
    loop
    x := x + i*ascii (substr (str, i, 1)) ;
    end loop;
    return x;
    end;
    /

    This function can be used in a SQL statement. For example, one may insert the codes as: update mappings set sleutel = sumascii(mapping);

  • Handy PLSQL programme

    This programme uses PLSQL to select a set of 1000 records per item. Each item is calculated from a cursor that generates the items for which a set of records is calculated.

    So the programme can be written in pseudo code as:

    • For i:=1 to NumberItem
    • calculate set
    • end Loop

    The programme looks like:

    create or replace PROCEDURE SP_VEXISTABLA2
     IS
     stmt varchar2(1000);
     TELLER NUMBER(3);
         --Declare the cursor
     CURSOR Product IS
           select distinct  "Steering View Deal ListOfValue" from DCL_FINAL_OUTCOME;
         Target  DCL_FINAL_OUTCOME."Steering View Deal ListOfValue"%TYPE;
    begin
    stmt:= 'drop table DCL_DT_CORE_DAX0329_ALL';   
    SELECT COUNT(*) INTO teller FROM user_tables WHERE table_name = UPPER('DCL_DT_CORE_DAX0329_ALL');
    IF (teller>0) THEN 
       execute immediate stmt;
     END IF;
    stmt:= 'create table DCL_DT_CORE_DAX0329_ALL as select * from DCL_FINAL_OUTCOME where 1=0';
     execute immediate stmt;
     
    OPEN Product;
    --Begin the Indefinite LOOP
    LOOP
        --Retrieve the CURSOR data into the holding object
        FETCH Product INTO Target;
    dbms_output.put_line('Verwerkt product: '|| Target);        
        --Test whether a record was found
        EXIT WHEN Product%NOTFOUND;
    
      stmt := q'!INSERT INTO  DCL_DT_CORE_DAX0329_!' ||'ALL'|| q'! 
        SELECT DISTINCT * from
                (select * FROM  DCL_FINAL_OUTCOME
                where trim("Steering View Deal ListOfValue")=trim('!' ||Target||q'!') and mandant=309
                ORDER BY dbms_random.value)
                WHERE
                rownum <= 100
    
    
                UNION ALL
    
                SELECT DISTINCT  * from
                (select *  FROM  DCL_FINAL_OUTCOME
                where trim("Steering View Deal ListOfValue")=trim('!' ||Target||q'!') and mandant!=309
                ORDER BY dbms_random.value)
                WHERE
                rownum <= 900!';
    dbms_output.put_line(stmt);
     execute immediate stmt;
     END LOOP;
    
    --Close the CURSOR
    CLOSE Product;
    commit;
    EXCEPTION
         WHEN OTHERS THEN
           dbms_output.put_line('Oops foutje');  
           dbms_output.put_line('SQL Code '||SQLCODE);  
           dbms_output.put_line('Message  '||SQLERRM); 
    end;
     /
    

  • Giving values to primary key

    Let us see how we might provide a value to the primary key in Oracle. There are many ways to provide a value for the primary key. One is to create a trigger (see https://archief.van-maanen.com/index.php/2011/02/02/create-a-surrogate-key-in-oracle/ ). Another is to declare a field as an identity field (id NUMBER GENERATED ALWAYS AS IDENTITY,) . A third way is to create a sequence that is used to load unique values into that primary key field.

    Let me provide an example to load such field. The field is loaded with the NEXTVAL field of a sequence. Then the value is created first. Then the value is loaded into the field that contains the primary key.

    DECLARE
      NewUserID   employee.empid%TYPE;
    BEGIN
      NewUserID := EmpIDSequence.NEXTVAL;
      INSERT INTO employee (dno, empid)  VALUES( 5, NewUserID);
    END;
    /

    Another example is direct usage in an insert statement of a sequence object. Recently this possibility to use sequence objects in inserts is introduced in Oracle.

    INSERT INTO USERS    VALUES ( 'John',    UsrIDSeq.NEXTVAL); 
  • PL SQL that creates a table

    The situation is simple. We have to create a table that contain data on a certain variable outcome. Normally, one would like to create a field in the table and add a bunch of records that relate to that outcome. However, the request is to create a new table for that. Examples might be a new table for a certain month, certain country etc.

    Reluctantly, we agree and we create a procedure that create a new table for each occurance of a value.

    The code looks like:

    set serveroutput on
    create or replace PROCEDURE SP_VEXISTABLA(TAAK IN VARCHAR)
    IS
    stmt varchar2(1000);
    TELLER NUMBER(3);
    begin
    SELECT COUNT(*) INTO TELLER FROM USER_TABLES WHERE TABLE_NAME = 'D' || TAAK;
    IF (TELLER >0) THEN
    execute immediate 'DROP TABLE D' || TAAK;
    END IF;
    stmt := q'!CREATE TABLE D!' ||taak|| q'! AS
    (SELECT *
    FROM ( SELECT DISTINCT ding, mandant, rest
    FROM opdeel
    where trim(ding)=trim('!' ||taak||q'!') and mandant=309
    ORDER BY dbms_random.value)
    WHERE
    rownum <= 2)!';
    dbms_output.put_line(stmt);
    execute immediate stmt;
    end;
    /

    The code to run this is as follows:

    exec HR.SP_VEXISTABLA('CL');
  • Hot backup in Oracle

    It is possible to make a hot backup in Oracle. This implies that we do not have to shutdown the database before creating a backup.

    The steps are as follows:

    First, we check if the system is in an archive mode:

    archive log list

    This command is given in sqlplus when logged in as sysdba. The answer from the system should be something like “Database log mode Archive Mode”. This indicates that archive files are created. The files look like “ARC0000000197_0999381692.0001” in a directory. In my case the directory is “C:\app\tmaanen\product\12.1.0\dbhome_1\RDBMS”.

    We also must verify where the datafiles are stored. This can be checked with:

    select file_id, file_name from dba_data_files;

    We can then check which archive log is relevant:

    select group#, sequence#, status from v$log;

    Now, we can start the backup:

    alter database begin backup;
    alter system switch logfile;

    Now copy all datafiles (*.dbf) , all archive files (ARC*.*) and the controlfiles.

    Then continue the system:

    alter database end backup;

    To restore the database, we must take several steps:

    First, shutdown the instance:

    shutdown immediate

    Copy the *.dbf files to the datafile locatipon. Copy the controlfiles to controlfile location. Copy the archive files to the archive location.

    Then start Oracle in the mount status:

    startup mount;
    recover database until cancel using backup controlfile;

    With the latter command, we must indicate “AUTO”.

    We start the database with

    alter database open resetlogs;

    This should provide the consistent database on the moment when database was backed up.

  • Cold backup in Oracle

    Actually, taking a cold backup in Oracle is quite simple. If you choose to undertake a cold backup by copying tables, it consists of 5 steps.

    Step 1 is identifying the location of the data files. We have 3 commands for that:

    select name from v$datafile;
    select member from v$logfile;
    select name from v$controlfile;

    We must remember these files for later copying actions.

    Step 2 is making a copy of the spfile by:

    create pfile from spfile;

    This will create a PFILE named initSID.ora in your $ORACLE_HOME/database (Windows) or $ORACLE_HOME/dbs (Linux/Unix) directory.

    Step 3 is forcing Oracle to create a checkpoint:

    alter system switch logfile;

    Step 4 is to stop the Oracle instance:

    shutdown immediate

    Step 5 is copying all files as identified in step 1 and the pfile from step 2 into a safe place.

    This leads to a situation where we have a bunch of files that we can use to restore the database. Another possibility is to clone the database in another instance. I tried this by installing an Oracle instance elsewhere and copy the files to its appropiate location. However, I noticed that I had to use the exact same version of Oracle, the same folder structure and the same platform.

    So I used Oracle 12 release 1 on Windows 10 with an identical folder structure as the original Oracle 12 release 1. I then copied the files from above to the new instance and voila: it worked. Two times the same Oracle instance and database.

    This copying action was undertaken with both instances being shutdown. So it was a cold backup from instance 1 that was restored in instance 2.

  • Changing granularity

    Let us suppose, we have a table that has a granularity in two dimensions. Think of a customer and a product dimension. So each record has a combination of customer identification and product identification that is unique. Let us also assume that we would decrease that level of granularity into one dimension. Think of customer that should act as the identifying dimension. Each product identification should have its own column.

    Let us provide an example. The start situation is as follows:


    The target situation is:

    We have the code for the table here:

    CREATE TABLE pivot_test (
    id NUMBER,
    customer_id NUMBER,
    product_code VARCHAR2(5),
    quantity NUMBER
    );
    INSERT INTO pivot_test VALUES (1, 1, 'A', 10);
    INSERT INTO pivot_test VALUES (2, 1, 'B', 20);
    INSERT INTO pivot_test VALUES (3, 1, 'C', 30);
    INSERT INTO pivot_test VALUES (4, 2, 'A', 40);
    INSERT INTO pivot_test VALUES (5, 2, 'C', 50);
    INSERT INTO pivot_test VALUES (6, 3, 'A', 60);
    INSERT INTO pivot_test VALUES (7, 3, 'B', 70);
    INSERT INTO pivot_test VALUES (8, 3, 'C', 80);
    INSERT INTO pivot_test VALUES (9, 3, 'D', 90);
    INSERT INTO pivot_test VALUES (10, 4, 'A', 100);
    COMMIT;

    There are two solutions for this:

    Solution 1 uses the pivot function:

    SELECT "CUSTOMER_ID" , 
    "A_SUM_QUANTITY" ,
    "B_SUM_QUANTITY" ,
    "C_SUM_QUANTITY"
    FROM (SELECT customer_id, product_code, quantity
    FROM pivot_test)
    PIVOT (SUM(quantity) AS sum_quantity FOR (product_code) IN ('A' AS a, 'B' AS b, 'C' AS c))
    ORDER BY customer_id;

    Solution 2 uses a decode function:

    SELECT customer_id,
    SUM(DECODE(product_code, 'A', quantity, 0)) AS a_sum_quantity,
    SUM(DECODE(product_code, 'B', quantity, 0)) AS b_sum_quantity,
    SUM(DECODE(product_code, 'C', quantity, 0)) AS c_sum_quantity
    FROM pivot_test
    GROUP BY customer_id
    ORDER BY customer_id;
  • Working with XML in Oracle

    Oracle has nice features to export data as an XML file. Let us discuss a few of them.

    The first one is to use SQL Developer. We could already export a table in SQL developer as an XML file.

    The second one is to use the DBMS_XMLGEN package. This allows to use queries in an export. Let me show some code to demonstrate this.

    SELECT DBMS_XMLGEN.GETXML(
    'SELECT EMPLOYEE_ID
    , LAST_NAME
    , DEPARTMENT_ID
    FROM employees
    WHERE DEPARTMENT_ID < 101')
    "XML OUTPUT"
    FROM dual;

    This creates output that can be inserted into an XML file. This can be read by a XML reader, such as Altova XMLSpy:

    XML

    A third possibility is to work with a stored procedure. The code can be found here.

    One may notice that this stored procedure also uses the DBMS_XMLGEN.GETXML package.

    A fourth possibility is to use this statement:

    select xmlelement( "Emp", xmlforest( first_name, last_name, salary ) ) from hr.employees;

    To get this displayed properly in sqlplus, we need to issue three commands:

    set serveroutput on
    set pages 50000
    set long 100000000

    This leads to a nice readable result:

    nice readable result

    Then possibility number 5. It is interesting to see that one has many possibilities to write a table or a query as XML. I read this possibility:

    select dbms_xmlgen.getxmltype('select * from employees') from dual;

  • External tables in Oracle

    External tables allow someone to store data in a file while these files are shown as tables within Oracle. So, we have a two sided object – on one hand it can be shown as a file that is human readable, on the other hand it can be seen as a table. Let us see at the list of files on a hard disk somewhere:

    Files line info.dat, info2.dat, dataDeal.txt are ordinary files that can be read. On the other hand, we have tables in Oracle that show like:

    The Oracle system has the concept of external files. The code to create these is:

    drop table dataDeal;
    CREATE TABLE dataDeal
    (
    TECHNICAL_KEY NUMBER(10),
    ID_ERSTE_ENT NUMBER(10),
    EDT_DEAL DATE,
    SDT_DEAL DATE,
    UNQ_ID_SRC_SYS VARCHAR2(50),
    LV_G_PRD_L3 VARCHAR2(25),
    LVW_FIN_AMT_TP VARCHAR2(25),
    LV_CCY VARCHAR2(25),
    AMT  NUMBER(18)
    )
    ORGANIZATION EXTERNAL
    (TYPE ORACLE_LOADER
     DEFAULT DIRECTORY external
    ACCESS PARAMETERS
    (RECORDS DELIMITED BY NEWLINE
    SKIP 1
    BADFILE 'bad_%a_%p.bad' 
    LOGFILE 'log_%a_%p.log' 
     fields terminated by '\t'
      MISSING FIELD VALUES ARE NULL
     ( TECHNICAL_KEY
    , ID_ERSTE_ENT
    ,EDT_DEAL date'dd.mm.yy' 
    ,SDT_DEAL date'dd.mm.yy'
    ,UNQ_ID_SRC_SYS
    ,LV_G_PRD_L3 
    ,LVW_FIN_AMT_TP 
    ,LV_CCY 
    ,AMT
    )
    )
     LOCATION (external:'dataDeal - Copy.txt')
    );
    
    select * from dataDeal;
    select count(*) from dataDeal;
    
    
    CREATE TABLE emp_load
          (employee_number      CHAR(5),
           employee_dob         CHAR(20),
           employee_last_name   CHAR(20),
           employee_first_name  CHAR(15),
           employee_middle_name CHAR(15),
           employee_hire_date   DATE)
        ORGANIZATION EXTERNAL
          (TYPE ORACLE_LOADER
          DEFAULT DIRECTORY EXTERNAL
          ACCESS PARAMETERS
            (RECORDS DELIMITED BY NEWLINE
             FIELDS (employee_number      CHAR(2),
                     employee_dob         CHAR(20),
                     employee_last_name   CHAR(18),
                     employee_first_name  CHAR(11),
                     employee_middle_name CHAR(11),
                     employee_hire_date   CHAR(10) date_format DATE mask "mm/dd/yyyy"
                    )
            )
          LOCATION ('info.dat')
         );
     
     drop table emp_load2;
     CREATE TABLE emp_load2
          (employee_number      CHAR(5),
           employee_dob         CHAR(20),
           employee_last_name   CHAR(20),
           employee_first_name  CHAR(15),
           employee_middle_name CHAR(15),
           employee_hire_date   DATE)
        ORGANIZATION EXTERNAL
          (TYPE ORACLE_LOADER
          DEFAULT DIRECTORY EXTERNAL
          ACCESS PARAMETERS
            (RECORDS DELIMITED BY NEWLINE
            fields terminated by ';'
              (employee_number      ,
                     employee_dob         ,
                     employee_last_name   ,
                     employee_first_name  ,
                     employee_middle_name ,
                     employee_hire_date     DATE'mm/dd/yyyy'
                    )
            )
          LOCATION ('info2.dat')
         );
        
         
         select employee_middle_name,to_char(employee_hire_date,'YYYY-MON-DD') from  emp_load2;
         
         
         drop table emp_load3;
     CREATE TABLE emp_load3
          (employee_number      CHAR(5),
           employee_dob         CHAR(20),
           employee_last_name   CHAR(20),
           employee_first_name  CHAR(15),
           employee_middle_name CHAR(15),
           employee_hire_date   DATE)
        ORGANIZATION EXTERNAL
          (TYPE ORACLE_LOADER
          DEFAULT DIRECTORY EXTERNAL
          ACCESS PARAMETERS
            (RECORDS DELIMITED BY NEWLINE
            fields terminated by '\t'
              (employee_number      ,
                     employee_dob         ,
                     employee_last_name   ,
                     employee_first_name  ,
                     employee_middle_name ,
                     employee_hire_date     DATE'mm/dd/yyyy'
                    )
            )
          LOCATION ('info3.dat')
         );
        
         
         select employee_middle_name,to_char(employee_hire_date,'YYYY-MON-DD') from  emp_load3;
    

    One only needs to create a directory for which the parameter value is:

    Finally: the files can be found here