Category: Allgemein

  • Using Python to read and write in a SQL Server database

    Below, I provide a snippet to read data from an Azure SQL Server database. Subsequently, it is written to another table in the same database.

    The trick here is to read the data, store them in a matrix which will be written out to a second table. Elements within the matrix can be accessed with results[i][j].

    import pyodbc 
    conn = pyodbc.connect('DSN=AzureSQL;UID=tomvanmaanen;PWD=********')
    data = []
    cursor = conn.cursor()
    cursor.execute('SELECT [CODE],[DESCRIPTION],[START_DATE],[END_DATE] FROM STAGINGZONE.T01_brp_country_code')
    columns = [column[0] for column in cursor.description]
    results = [columns] + [row for row in cursor.fetchall()]
    for x in range(len(results)):
       Sql_insert_query = "INSERT INTO dbo.ff (test) VALUES ('" + results[x][1].replace("'", " ") + "')"
       cursor.execute(Sql_insert_query)
    conn.commit()
    cursor.close()
  • Hierarchical query in Oracle

    Below, you find a nice example of an hierarchical query in Oracle. The idea is that you see the top-down hierarchy with some indications on the level that is shown.

    First the query:

    select  level,
            case 
            when level=1 then first_name||' '||last_name 
            when level>1 then lpad (first_name||' '||last_name,length(first_name||' '||last_name)+level-1, '-')
            end tree
    from employees  
    start with employee_id=100
    connect by prior employee_id=manager_id --top down 

    The result is straight forward to interpret:

    The level is provided, with dashes to provide additional information.

    The query can be undertaken from top to bottom as shown here. The idea is that starts with the top, going down to the lower levels. However if the foreign key and primary key are reversed, one starts the analysis from a person to the top, like:

    select  level,
    case
    when level=1 then first_name||' '||last_name
    when level>1 then lpad (first_name||' '||last_name,length(first_name||' '||last_name)+level-1, '-')
    end tree
    from employees
    start with employee_id=113
    connect by prior manager_id=employee_id -- down-top

    , which then leads to another view:

  • Size on Oracle

    What is the size of an Oracle table? A very rough approximation is to multiply the number of rows with the average row length in bytes. Fortunately, Oracle directly provide you with such information. Take this query:

    select 
    table_name
    , num_rows
    , avg_row_len
    ,to_char((num_rows * avg_row_len)/1000000,'9999999D999','NLS_NUMERIC_CHARACTERS=''. ''') as sizeMB
    , blocks  
    from dba_tab_statistics where owner like 'ST%';

    This can be verified in SQL Developer when you investigate the tablespaces:

  • Running totals in Oracle

    Oracle has a nice possibility to calculate running totals. Assume we have a sales system where transactions are stored over time. We would like to know the running total – what is sold until a certain transaction.

    The code to calculate this is:

    SELECT  trans_id,to_char(trans_date,'dd-mm-yyyy hh24:mi:ss' ) trans_date ,
    product_code ,qty* price amount,
    sum(qty* price) over ( order by trans_id ) runing_total
    from supermarket_trans 
    where trunc(TRANS_DATE)=trunc(sysdate)

    which provides:

  • A completely useless PL SQL programme

    Once, I wrote a completely useless programme – see below. I like to retain it as I spent quite some time on it. But it is absolutely useless.

    The idea it that we have some kind of a counter that is incremented by 1 if a subsequent record has the same value for a particular field. It needs to be reset at 1 in case of a new value.

    I wrote a nice PL SQL programme to do this.

    However Oracle has three functions that would have led to the same result: a lag function, a row_number analytical function and a rank function. So, useless, useless. But it was fun programming.

    declare
    cursor c_emp is select * from stagingzone.T9_EMPLOYMENT ;
    r_emp c_emp%ROWTYPE;
    ff_Person_ID number := 0;
    ff_Employment_ID number := 0;
    volgno number := 0;
    volg number := 0;
    stmt varchar(1000);
    stmt1 varchar(1000):=”;
    teller number :=0;
    hx varchar(35);
    hx1 varchar(35);
    begin
    stmt:= ‘drop table stagingzone.EMPLOYMENT_BU’;
    SELECT COUNT(*) into TELLER FROM all_tables WHERE table_name = UPPER(‘EMPLOYMENT_BU’) and owner = UPPER(‘STAGINGZONE’);
    IF (teller>0) THEN
    dbms_output.put_line(stmt);
    execute immediate stmt;
    END IF;
    stmt:= ‘create table stagingzone.EMPLOYMENT_BU as select * FROM stagingzone.T9_EMPLOYMENT where 1=0’;
    dbms_output.put_line(stmt);
    execute immediate stmt;
    teller:=0;
    open c_emp;
    loop
    fetch c_emp into r_emp;
    teller := teller + 1;
    exit when c_emp%NOTFOUND ;
    hx:=q'[to_date(‘]’||to_char(r_emp.START_DATE_EMPLOYMENT,’DDMMYYYY’)||q'[‘,’DDMMYYYY’)]’;
    hx1:=q'[to_date(‘]’||to_char(r_emp.END_DATE_EMPLOYMENT,’DDMMYYYY’)||q'[‘,’DDMMYYYY’)]’;
    if (r_emp.PERSON_ID=ff_Person_ID)
    then volgno := volgno + 1;
    else volgno :=1;
    end if;
    if (r_emp.PERSON_ID=ff_Person_ID and r_emp.EMPLOYMENT_ID =ff_Employment_ID)
    then volg := volg + 1;
    else volg :=1;
    end if;
    r_emp.SEQUENCE_NUMBER_EMPLOYMENT := volg;
    r_emp.SEQUENCE_NUMBER :=volgno;
    ff_Person_ID:=r_emp.PERSON_ID;
    ff_Employment_ID:=r_emp.EMPLOYMENT_ID;
    stmt1 := q'[INSERT INTO stagingzone.EMPLOYMENT_BU(PERSON_ID,START_DATE_EMPLOYMENT ,END_DATE_EMPLOYMENT ,SEQUENCE_NUMBER_EMPLOYMENT, SEQUENCE_NUMBER, EMPLOYER_ID, EMPLOYMENT_ID) values(]’||
    r_emp.PERSON_ID||’,’||hx||’,’||hx1||’,’||r_emp.SEQUENCE_NUMBER_EMPLOYMENT||’,’||r_emp.SEQUENCE_NUMBER ||’,’||r_emp.EMPLOYER_ID ||’,’||r_emp.EMPLOYMENT_ID ||’)’;
    — if mod(teller,100) = 0 then dbms_output.put_line(stmt1);end if;
    execute immediate stmt1;
    end loop;
    close c_emp;
    EXCEPTION
    WHEN OTHERS THEN
    dbms_output.put_line(‘Oops foutje’);
    dbms_output.put_line(‘SQL Code ‘||SQLCODE);
    dbms_output.put_line(‘Message ‘||SQLERRM);
    end;
    /

  • Ranking in Oracle

    Oracle has 3 analytical functions to rank data. They provide approximately the same results, but with little deviations.

    First the code:

    select salary,
    rank() over (order by salary) rank,
           dense_rank() over (order by salary) dense_rank,
           row_number() over (order by salary) row_number
           from hr.employees
           order by salary;

    Inspecting the results shows the deviations. Look at the ties

  • Top 10 rows in Oracle

    In previous versions of Oracle, we had to retrieve a top10 rows via a sub query. In the sub query, we ordered and retrieved the data whereas in the main query, we could retrieve 10 top rows. Something like:

    select * from
    (select * from hr.employees order by salary desc)
    where rownum <=10;

    Oracle 12 introduced a new concept that yields the same results:

    select * from hr.employees order by salary desc
    fetch first 10 rows  with ties;

    Pretty, isn’t it?

  • External table

    An external table is a flat file outside the Oracle database. If properly described in Oracle, it can be read as an Oracle table.

    The syntax consists of 3 elements:

    • a create table part
    • an ORGANIZATION EXTERNAL part that indicates that we are discussing an external table
    • a set of attributes that discusses
      • how the data are read (ORACLE_LOADER),
      • how the data are accessed – between parenthesis you find how the records are read, how the fields are separated and
      • what the fields are and
      • finally what the location is.
    CREATE TABLE fam_external_table
     (
     nmbr NUMBER,
     fname VARCHAR2(10),
     lname VARCHAR2(20)
     )
     ORGANIZATION EXTERNAL
     (
     TYPE ORACLE_LOADER DEFAULT DIRECTORY EXTERN
     ACCESS PARAMETERS (RECORDS DELIMITED BY NEWLINE
     FIELDS terminated BY ";"
     REJECT ROWS WITH ALL NULL
     FIELDS(nmbr, fname,lname) )
     LOCATION ('familie.txt')
     );

    Doing so, we the data as a normal Oracle table:

    A brilliant example is given in https://asktom.oracle.com/pls/asktom/asktom.search?tag=external-tables-200206

    A nice feature is provided in SQL Developer. Via the import facility one may generate an external file. The usage is straight forward.

    The generated script then looks like:

    –CREATE OR REPLACE DIRECTORY EXTERNORA AS ‘C:\Users\tomva\externora’;
    –GRANT READ ON DIRECTORY EXTERNORA TO USER;
    –GRANT WRITE ON DIRECTORY EXTERNORA TO USER;
    –drop table PRUT;
    CREATE TABLE PRUT
    ( EMPLOYEE_ID NUMBER(38),
    FIRST_NAME VARCHAR2(128),
    LAST_NAME VARCHAR2(128),
    EMAIL VARCHAR2(128),
    PHONE_NUMBER VARCHAR2(128),
    HIRE_DATE NUMBER(38),
    JOB_ID VARCHAR2(128),
    SALARY NUMBER(38),
    COMMISSION_PCT NUMBER(38, 2),
    MANAGER_ID NUMBER(38),
    DEPARTMENT_ID NUMBER(38))
    ORGANIZATION EXTERNAL
    ( TYPE ORACLE_LOADER
    DEFAULT DIRECTORY EXTERNORA
    ACCESS PARAMETERS
    (records delimited BY ‘\r\n’
    NOBADFILE
    NODISCARDFILE
    NOLOGFILE
    skip 1
    fields terminated BY ‘|’
    OPTIONALLY ENCLOSED BY ‘”‘ AND ‘”‘
    lrtrim
    missing field VALUES are NULL
    ( EMPLOYEE_ID CHAR(4000),
    FIRST_NAME CHAR(4000),
    LAST_NAME CHAR(4000),
    EMAIL CHAR(4000),
    PHONE_NUMBER CHAR(4000),
    HIRE_DATE CHAR(4000),
    JOB_ID CHAR(4000),
    SALARY CHAR(4000),
    COMMISSION_PCT CHAR(4000),
    MANAGER_ID CHAR(4000),
    DEPARTMENT_ID CHAR(4000)
    )
    )
    LOCATION (‘export.csv’)
    )
    REJECT LIMIT UNLIMITED;

  • Change strings in Oracle

    PL/SQL with the utl_file package allows us to manipulate strings in Oracle. One may read a string from a file, modify this and subsequently write it to another file. This opens nice possibilities.

    Let me show some code how to do this:

    DECLARE
    v_file_ptr utl_file.file_type;
    v_file_handler utl_file.file_type;
    v_line varchar2(2000);
    BEGIN
    v_file_ptr := utl_file.fopen('EXTERN','namen.txt','r');
    v_file_handler:= utl_file.fopen('EXTERN','uitvoer.txt','w');
    LOOP 
    BEGIN
    utl_file.get_line(v_file_ptr,v_line);
    utl_file.put_line(v_file_handler,'uitvoer >> ' || v_line);
    dbms_output.put_line(v_line);
    EXCEPTION WHEN NO_DATA_FOUND THEN EXIT; 
    END ;
    END LOOP;
    utl_file.fclose(v_file_ptr);
    utl_file.fclose(v_file_handler);
    EXCEPTION WHEN OTHERS THEN
    dbms_output.put_line(sqlcode||sqlerrm);
    END;
    /

    First, we open two file handlers: one to file from which we read and another to which some will be written.

    Subsequently, a loop starts that reads a file, line by line. Each line is manipulated and subsequently written to another file.

    Finally the file handlers are closed.

    This technique can also be used to create a simple HTML report:

    The actual query is “select first_name, last_name from employees”. The results are outputted is a for i loop. The results are written to file with HTML mark ups.

    For more information, see https://docs.oracle.com/database/121/ARPLS/u_file.htm#ARPLS70913

  • Oracle and JSON

    JSON stands for Java Script Object Notation. It is a way to describe and store data. It can be read and modified in any editor. It has components that describe the data and components that store the data. An example is subsequent line:

    {"job_id":"AD_PRES","job_title":"President","min_salary":20080,"max_salary":40000}

    Components like “job_id”, “job_title”, “min_salary”, “max_salary” describe the data, whereas “AD_PRES”, “President”, 20080, 40000 are actual data. Components like “{” and “}”provide a begin and an end respectively. The colon provides the relation between a description and actual data. A comma provides a separation between the elements in one object.

    Oracle knows how to query such a JSON file. One may insert JSON statements in a table and subsequently query it. The DDL to set up such table is:

    CREATE TABLE "HR"."JSON_DATA" 
       (    "UNIQUE_ID" NUMBER, 
            "JSON_COL" CLOB, 
            CONSTRAINT "MUST_BE_JSON" CHECK (json_col IS JSON) ENABLE
       );

    This table has one constraint: whatever is stored in the json_col must comply to JSON rules. When one tries to insert something non-compliant, an error ORA-02290 is thrown.

    One may insert records with standard insert statements, like:

    Insert into HR.JSON_DATA (UNIQUE_ID, json_col) values ('11','{"job_id":"PU_CLERK","job_title":"Purchasing Clerk","min_salary":2500,"max_salary":5500}');

    When a table is loaded with such statements, one may start querying it:

    select J.json_col.job_title from json_data j;

    In such query, a dot notation is followed. One recognizes the table, the column and the describing element that allows to retrieve a particular set of values.