Quantcast
Channel: Database – ViralPatel.net
Viewing all 25 articles
Browse latest View live

Oracle XMLTable Tutorial with Example

$
0
0
oracle-xmltable-example Since Oracle 10g, Oracle has added new functions XQuery and XMLTable to its arsenal of XML processing APIs. XMLQuery lets you construct XML data and query XML and relational data using the XQuery language. XMLTable lets you create relational tables and columns from XQuery query results. Oracle XMLTable Tutorial In this post we will learn about Oracle XMLTable function. The best way to learn is to learn by example. This way you can quickly understand different aspect of the API. So lets start with our example. Consider a table EMPLOYEES which holds some XML data. Below is the create statement this table.
CREATE TABLE EMPLOYEES
(
   id     NUMBER,
   data   XMLTYPE
);
Now the table is ready. Lets insert a record in it. Below INSERT statement add one record having some XML content in it.
INSERT INTO EMPLOYEES
     VALUES (1, xmltype ('<Employees>
    <Employee emplid="1111" type="admin">
        <firstname>John</firstname>
        <lastname>Watson</lastname>
        <age>30</age>
        <email>johnwatson@sh.com</email>
    </Employee>
    <Employee emplid="2222" type="admin">
        <firstname>Sherlock</firstname>
        <lastname>Homes</lastname>
        <age>32</age>
        <email>sherlock@sh.com</email>
    </Employee>
    <Employee emplid="3333" type="user">
        <firstname>Jim</firstname>
        <lastname>Moriarty</lastname>
        <age>52</age>
        <email>jim@sh.com</email>
    </Employee>
    <Employee emplid="4444" type="user">
        <firstname>Mycroft</firstname>
        <lastname>Holmes</lastname>
        <age>41</age>
        <email>mycroft@sh.com</email>
    </Employee>
</Employees>'));
Notice the XML contains employee related data. Before we start lets check few facts from above xml.
  1. There are 4 employees in our xml file
  2. Each employee has a unique employee id defined by attribute emplid
  3. Each employee also has an attribute type which defines whether an employee is admin or user.
  4. Each employee has four child nodes: firstname, lastname, age and email
  5. Age is a number
Now we can use Oracle XMLTable function to retrieve different information from this XML. Let’s get started…

1. Learning XPath Expressions

Before we start with Oracle XMLTable function it is good to know a bit about XPath. XPath uses a path expression to select nodes or list of node from a xml document. Heres a list of useful paths and expression that can be used to select any node/nodelist from a xml document.
Expression Description
nodename Selects all nodes with the name “nodename”
/ Selects from the root node
// Selects nodes in the document from the current node that match the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes
employee Selects all nodes with the name “employee”
employees/employee Selects all employee elements that are children of employees
//employee Selects all employee elements no matter where they are in the document
Below list of expressions are called Predicates. The Predicates are defined in square brackets [ ... ]. They are used to find a specific node or a node that contains a specific value.
Path Expression Result
/employees/employee[1] Selects the first employee element that is the child of the employees element.
/employees/employee[last()] Selects the last employee element that is the child of the employees element
/employees/employee[last()-1] Selects the last but one employee element that is the child of the employees element
//employee[@type='admin'] Selects all the employee elements that have an attribute named type with a value of ‘admin’
There are other useful expressions that you can use to query the data. Read this w3school page for more details: http://www.w3schools.com/xpath/xpath_syntax.asp

2. Learning Basics of Oracle XMLTable function

Lets get started with Oracle XMLTable function. Below are few examples of using different expressions of XPath to fetch some information from xml document.

2.1 Read firstname and lastname of all employees

In this query, we using XMLTable function to parse the XML content from Employees table.
--print firstname and lastname of all employees 
   SELECT t.id, x.*
     FROM employees t,
          XMLTABLE ('/Employees/Employee'
                    PASSING t.data
                    COLUMNS firstname VARCHAR2(30) PATH 'firstname', 
                            lastname VARCHAR2(30) PATH 'lastname') x
    WHERE t.id = 1;
Note the syntax of XMLTable function:
XMLTable('<XQuery>' 
         PASSING <xml column>
         COLUMNS <new column name> <column type> PATH <XQuery path>)
The XMLTABLE function contains one row-generating XQuery expression and, in the COLUMNS clause, one or multiple column-generating expressions. In Listing 1, the row-generating expression is the XPath /Employees/Employee. The passing clause defines that the emp.data refers to the XML column data of the table Employees emp. The COLUMNS clause is used to transform XML data into relational data. Each of the entries in this clause defines a column with a column name and a SQL data type. In above query we defined two columns firstname and lastname that points to PATH firstname and lastname or selected XML node. Output: oracle-xmltables-query2

2.2 Read node value using text()

In above example we read the content of node firstname / lastname. Sometimes you may want to fetch the text value of currently selected node item. In below example we will select path /Employees/Employee/firstname. And then use text() expression to get the value of this selected node. Below query will read firstname of all the employees.
--print firstname of all employees
   SELECT t.id, x.*
     FROM employees t,
          XMLTABLE ('/Employees/Employee/firstname'
                    PASSING t.data
                    COLUMNS firstname VARCHAR2 (30) PATH 'text()') x
    WHERE t.id = 1;
Output: oracle-xmltables-query1 Along with text() expression, Oracle provides various other useful expressions. For example item(), node(), attribute(), element(), document-node(), namespace(), text(), xs:integer, xs:string.

2.3 Read Attribute value of selected node

We can select an attribute value in our query. The attribute can be defined in XML node. In below query we select attribute type from the employee node.
--print employee type of all employees
   SELECT emp.id, x.*
     FROM employees emp,
          XMLTABLE ('/Employees/Employee'
                    PASSING emp.data
                    COLUMNS firstname VARCHAR2(30) PATH 'firstname',
                            type VARCHAR2(30) PATH '@type') x;
Output: oracle xmltable attributes

2.3 Read specific employee record using employee id

--print firstname and lastname of employee with id 2222 
   SELECT t.id, x.*
     FROM employees t,
          XMLTABLE ('/Employees/Employee[@emplid=2222]'
                    PASSING t.data
                    COLUMNS firstname VARCHAR2(30) PATH 'firstname', 
                            lastname VARCHAR2(30) PATH 'lastname') x
    WHERE t.id = 1;
Output: oracle-xmltables-query3

2.4 Read firstname lastname of all employees who are admins

--print firstname and lastname of employees who are admins 
   SELECT t.id, x.*
     FROM employees t,
          XMLTABLE ('/Employees/Employee[@type="admin"]'
                    PASSING t.data
                    COLUMNS firstname VARCHAR2(30) PATH 'firstname', 
                            lastname VARCHAR2(30) PATH 'lastname') x
    WHERE t.id = 1;
Output: oracle-xmltables-query4

2.5 Read firstname lastname of all employees who are older than 40 year

--print firstname and lastname of employees having age > 40
   SELECT t.id, x.*
     FROM employees t,
          XMLTABLE ('/Employees/Employee[age>40]'
                    PASSING t.data
                    COLUMNS firstname VARCHAR2(30) PATH 'firstname', 
                            lastname VARCHAR2(30) PATH 'lastname',
                            age VARCHAR2(30) PATH 'age') x
    WHERE t.id = 1;
Output: oracle-xmltables-query5

Reference


45 Useful Oracle Queries

$
0
0
useful-oracle-queries Here’s a list of 40+ Useful Oracle queries that every Oracle developer must bookmark. These queries range from date manipulation, getting server info, get execution status, calculate database size etc.

Date / Time related queries

  1. Get the first day of the month

    Quickly returns the first day of current month. Instead of current month you want to find first day of month where a date falls, replace SYSDATE with any date column/value.
    SELECT TRUNC (SYSDATE, 'MONTH') "First day of current month" 
        FROM DUAL;
    
  2. Get the last day of the month

    This query is similar to above but returns last day of current month. One thing worth noting is that it automatically takes care of leap year. So if you have 29 days in Feb, it will return 29/2. Also similar to above query replace SYSDATE with any other date column/value to find last day of that particular month.
    SELECT TRUNC (LAST_DAY (SYSDATE)) "Last day of current month" 
        FROM DUAL;
    
  3. Get the first day of the Year

    First day of year is always 1-Jan. This query can be use in stored procedure where you quickly want first day of year for some calculation.
    SELECT TRUNC (SYSDATE, 'YEAR') "Year First Day" FROM DUAL;
    
  4. Get the last day of the year

    Similar to above query. Instead of first day this query returns last day of current year.
    SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL
    
  5. Get number of days in current month

    Now this is useful. This query returns number of days in current month. You can change SYSDATE with any date/value to know number of days in that month.
    SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_days
      FROM DUAL;
    
  6. Get number of days left in current month

    Below query calculates number of days left in current month.
    SELECT SYSDATE,
           LAST_DAY (SYSDATE) "Last",
           LAST_DAY (SYSDATE) - SYSDATE "Days left"
      FROM DUAL;
    
  7. Get number of days between two dates

    Use this query to get difference between two dates in number of days.
    SELECT ROUND ( (MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0)
              num_of_days
      FROM DUAL;
    
    OR
    
    SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees;
    
    Use second query if you need to find number of days since some specific date. In this example number of days since any employee is hired.
  8. Display each months start and end date upto last month of the year

    This clever query displays start date and end date of each month in current year. You might want to use this for certain types of calculations.
    SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date,
           TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_date
      FROM XMLTABLE (
              'for $i in 0 to xs:int(D) return $i'
              PASSING XMLELEMENT (
                         d,
                         FLOOR (
                            MONTHS_BETWEEN (
                               ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),
                               SYSDATE)))
              COLUMNS i INTEGER PATH '.');
    
  9. Get number of seconds passed since today (since 00:00 hr)

    SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning
      FROM DUAL;
    
  10. Get number of seconds left today (till 23:59:59 hr)

    SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left
      FROM DUAL;
    

    Data dictionary queries

  11. Check if a table exists in the current database schema

    A simple query that can be used to check if a table exists before you create it. This way you can make your create table script rerunnable. Just replace table_name with actual table you want to check. This query will check if table exists for current user (from where the query is executed).
    SELECT table_name
      FROM user_tables
     WHERE table_name = 'TABLE_NAME';
    
  12. Check if a column exists in a table

    Simple query to check if a particular column exists in table. Useful when you tries to add new column in table using ALTER TABLE statement, you might wanna check if column already exists before adding one.
    SELECT column_name AS FOUND
      FROM user_tab_cols
     WHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
    
  13. Showing the table structure

    This query gives you the DDL statement for any table. Notice we have pass ‘TABLE’ as first parameter. This query can be generalized to get DDL statement of any database object. For example to get DDL for a view just replace first argument with ‘VIEW’ and second with your view name and so.
    SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;
    
  14. Getting current schema

    Yet another query to get current schema name.
    SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;
    
  15. Changing current schema

    Yet another query to change the current schema. Useful when your script is expected to run under certain user but is actually executed by other user. It is always safe to set the current user to what your script expects.
    ALTER SESSION SET CURRENT_SCHEMA = new_schema;
    

    Database administration queries

  16. Database version information

    Returns the Oracle database version.
    SELECT * FROM v$version;
    
  17. Database default information

    Some system default information.
    SELECT username,
           profile,
           default_tablespace,
           temporary_tablespace
      FROM dba_users;
    
  18. Database Character Set information

    Display the character set information of database.
    SELECT * FROM nls_database_parameters;
    
  19. Get Oracle version

    SELECT VALUE
      FROM v$system_parameter
     WHERE name = 'compatible';
    
  20. Store data case sensitive but to index it case insensitive

    Now this ones tricky. Sometime you might querying database on some value independent of case. In your query you might do UPPER(..) = UPPER(..) on both sides to make it case insensitive. Now in such cases, you might want to make your index case insensitive so that they don’t occupy more space. Feel free to experiment with this one.
    CREATE TABLE tab (col1 VARCHAR2 (10));
    
    CREATE INDEX idx1
       ON tab (UPPER (col1));
    
    ANALYZE TABLE a COMPUTE STATISTICS;
    
  21. Resizing Tablespace without adding datafile

    Yet another DDL query to resize table space.
    ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;
    
  22. Checking autoextend on/off for Tablespaces

    Query to check if autoextend is on or off for a given tablespace.
    SELECT SUBSTR (file_name, 1, 50), AUTOEXTENSIBLE FROM dba_data_files;
    
    (OR)
    
    SELECT tablespace_name, AUTOEXTENSIBLE FROM dba_data_files;
    
  23. Adding datafile to a tablespace

    Query to add datafile in a tablespace.
    ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/data01.dbf'
        SIZE 1000M AUTOEXTEND OFF;
    
  24. Increasing datafile size

    Yet another query to increase the datafile size of a given datafile.
    ALTER DATABASE DATAFILE '/u01/app/Test_data_01.dbf' RESIZE 2G;
    
  25. Find the Actual size of a Database

    Gives the actual database size in GB.
    SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;
    
  26. Find the size occupied by Data in a Database or Database usage details

    Gives the size occupied by data in this database.
    SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;
    
  27. Find the size of the SCHEMA/USER

    Give the size of user in MBs.
    SELECT SUM (bytes / 1024 / 1024) "size"
      FROM dba_segments
     WHERE owner = '&owner';
    
  28. Last SQL fired by the User on Database

    This query will display last SQL query fired by each user in this database. Notice how this query display last SQL per each session.
    SELECT S.USERNAME || '(' || s.sid || ')-' || s.osuser UNAME,
             s.program || '-' || s.terminal || '(' || s.machine || ')' PROG,
             s.sid || '/' || s.serial# sid,
             s.status "Status",
             p.spid,
             sql_text sqltext
        FROM v$sqltext_with_newlines t, V$SESSION s, v$process p
       WHERE     t.address = s.sql_address
             AND p.addr = s.paddr(+)
             AND t.hash_value = s.sql_hash_value
    ORDER BY s.sid, t.piece;
    

    Performance related queries

  29. CPU usage of the USER

    Displays CPU usage for each User. Useful to understand database load by user.
    SELECT ss.username, se.SID, VALUE / 100 cpu_usage_seconds
        FROM v$session ss, v$sesstat se, v$statname sn
       WHERE     se.STATISTIC# = sn.STATISTIC#
             AND NAME LIKE '%CPU used by this session%'
             AND se.SID = ss.SID
             AND ss.status = 'ACTIVE'
             AND ss.username IS NOT NULL
    ORDER BY VALUE DESC;
    
  30. Long Query progress in database

    Show the progress of long running queries.
    SELECT a.sid,
             a.serial#,
             b.username,
             opname OPERATION,
             target OBJECT,
             TRUNC (elapsed_seconds, 5) "ET (s)",
             TO_CHAR (start_time, 'HH24:MI:SS') start_time,
             ROUND ( (sofar / totalwork) * 100, 2) "COMPLETE (%)"
        FROM v$session_longops a, v$session b
       WHERE     a.sid = b.sid
             AND b.username NOT IN ('SYS', 'SYSTEM')
             AND totalwork > 0
    ORDER BY elapsed_seconds;
    
  31. Get current session id, process id, client process id?

    This is for those who wants to do some voodoo magic using process ids and session ids.
    SELECT b.sid,
           b.serial#,
           a.spid processid,
           b.process clientpid
      FROM v$process a, v$session b
     WHERE a.addr = b.paddr AND b.audsid = USERENV ('sessionid');
    
    • V$SESSION.SID AND V$SESSION.SERIAL# is database process id
    • V$PROCESS.SPID is shadow process id on this database server
    • V$SESSION.PROCESS is client PROCESS ID, ON windows it IS : separated THE FIRST # IS THE PROCESS ID ON THE client AND 2nd one IS THE THREAD id.
  32. Last SQL Fired from particular Schema or Table:

    SELECT CREATED, TIMESTAMP, last_ddl_time
      FROM all_objects
     WHERE     OWNER = 'MYSCHEMA'
           AND OBJECT_TYPE = 'TABLE'
           AND OBJECT_NAME = 'EMPLOYEE_TABLE';
    
  33. Find Top 10 SQL by reads per execution

    SELECT *
      FROM (  SELECT ROWNUM,
                     SUBSTR (a.sql_text, 1, 200) sql_text,
                     TRUNC (
                        a.disk_reads / DECODE (a.executions, 0, 1, a.executions))
                        reads_per_execution,
                     a.buffer_gets,
                     a.disk_reads,
                     a.executions,
                     a.sorts,
                     a.address
                FROM v$sqlarea a
            ORDER BY 3 DESC)
     WHERE ROWNUM < 10;
    
  34. Oracle SQL query over the view that shows actual Oracle connections.

    SELECT osuser,
             username,
             machine,
             program
        FROM v$session
    ORDER BY osuser;
    
  35. Oracle SQL query that show the opened connections group by the program that opens the connection.

    SELECT program application, COUNT (program) Numero_Sesiones
        FROM v$session
    GROUP BY program
    ORDER BY Numero_Sesiones DESC;
    
  36. Oracle SQL query that shows Oracle users connected and the sessions number for user

    SELECT username Usuario_Oracle, COUNT (username) Numero_Sesiones
        FROM v$session
    GROUP BY username
    ORDER BY Numero_Sesiones DESC;
    
  37. Get number of objects per owner

    SELECT owner, COUNT (owner) number_of_objects
        FROM dba_objects
    GROUP BY owner
    ORDER BY number_of_objects DESC;
    

    Utility / Math related queries

  38. Convert number to words

    More info: Converting number into words in Oracle
    SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;
    
    Output:
    one thousand five hundred twenty-six
    
  39. Find string in package source code

    Below query will search for string ‘FOO_SOMETHING’ in all package source. This query comes handy when you want to find a particular procedure or function call from all the source code.
    --search a string foo_something in package source code
    SELECT *
      FROM dba_source
     WHERE UPPER (text) LIKE '%FOO_SOMETHING%' 
    AND owner = 'USER_NAME';
    
  40. Convert Comma Separated Values into Table

    The query can come quite handy when you have comma separated data string that you need to convert into table so that you can use other SQL queries like IN or NOT IN. Here we are converting ‘AA,BB,CC,DD,EE,FF’ string to table containing AA, BB, CC etc. as each row. Once you have this table you can join it with other table to quickly do some useful stuffs.
    WITH csv
         AS (SELECT 'AA,BB,CC,DD,EE,FF'
                       AS csvdata
               FROM DUAL)
        SELECT REGEXP_SUBSTR (csv.csvdata, '[^,]+', 1, LEVEL) pivot_char
          FROM DUAL, csv
    CONNECT BY REGEXP_SUBSTR (csv.csvdata,'[^,]+', 1, LEVEL) IS NOT NULL;
    
  41. Find the last record from a table

    This ones straight forward. Use this when your table does not have primary key or you cannot be sure if record having max primary key is the latest one.
    SELECT *
      FROM employees
     WHERE ROWID IN (SELECT MAX (ROWID) FROM employees);
    
    (OR)
    
    SELECT * FROM employees
    MINUS
    SELECT *
      FROM employees
     WHERE ROWNUM < (SELECT COUNT (*) FROM employees);
    
  42. Row Data Multiplication in Oracle

    This query use some tricky math functions to multiply values from each row. Read below article for more details. More info: Row Data Multiplication In Oracle
    WITH tbl
         AS (SELECT -2 num FROM DUAL
             UNION
             SELECT -3 num FROM DUAL
             UNION
             SELECT -4 num FROM DUAL),
         sign_val
         AS (SELECT CASE MOD (COUNT (*), 2) WHEN 0 THEN 1 ELSE -1 END val
               FROM tbl
              WHERE num < 0)
      SELECT EXP (SUM (LN (ABS (num)))) * val
        FROM tbl, sign_val
    GROUP BY val;
    
  43. Generating Random Data In Oracle

    You might want to generate some random data to quickly insert in table for testing. Below query help you do that. Read this article for more details. More info: Random Data in Oracle
    SELECT LEVEL empl_id,
               MOD (ROWNUM, 50000) dept_id,
               TRUNC (DBMS_RANDOM.VALUE (1000, 500000), 2) salary,
               DECODE (ROUND (DBMS_RANDOM.VALUE (1, 2)),  1, 'M',  2, 'F') gender,
               TO_DATE (
                     ROUND (DBMS_RANDOM.VALUE (1, 28))
                  || '-'
                  || ROUND (DBMS_RANDOM.VALUE (1, 12))
                  || '-'
                  || ROUND (DBMS_RANDOM.VALUE (1900, 2010)),
                  'DD-MM-YYYY')
                  dob,
               DBMS_RANDOM.STRING ('x', DBMS_RANDOM.VALUE (20, 50)) address
          FROM DUAL
    CONNECT BY LEVEL < 10000;
    
  44. Random number generator in Oracle

    Plain old random number generator in Oracle. This ones generate a random number between 0 and 100. Change the multiplier to number that you want to set limit for.
    --generate random number between 0 and 100
    SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL;
    
  45. Check if table contains any data

    This one can be written in multiple ways. You can create count(*) on a table to know number of rows. But this query is more efficient given the fact that we are only interested in knowing if table has any data.
    SELECT 1
      FROM TABLE_NAME
     WHERE ROWNUM = 1;
    
If you have some cool query that can make life of other Oracle developers easy, do share in comment section.

How to pass CLOB argument in EXECUTE IMMEDIATE

$
0
0
clob argument in execute immediate oracle 11gWe know that Oracle EXECUTE IMMEDIATE statement implements Dynamic SQL in Oracle. It provides end-to-end support when executing a dynamic SQL statement or an anonymous PL/SQL block. Before Oracle 11g, EXECUTE IMMEDIATE supported SQL string statements up to 32K in length. Oracle 11g allows the usage of CLOB datatypes as an argument which eradicates the constraint we faced on the length of strings when passed as an argument to Execute immediate. Lets take an example to show how execute immediate failed for strings of size > 32K Example 1:
DECLARE
   var   VARCHAR2 (32767);
BEGIN
   var                          := 'create table temp_a(a number(10))';
-- to make a string of length > 32767 
   WHILE (LENGTH (var) < 33000)
   LOOP
      var                          := var || CHR (10) || '--comment';
   END LOOP;

   DBMS_OUTPUT.put_line (LENGTH (var));

   EXECUTE IMMEDIATE var;
END;
It will throw an obvious error : ORA-06502: PL/SQL: numeric or value error: character string buffer too small Lets start with how these scenarios were handled prior to introduction of CLOB argument in Execute Immediate DBMS_SQL was used with its inbuilt functions to take care of Dynamic SQL. Its inbuilt function PARSE was used to take care of dynamic SQL of 64k size. But it had certain drawbacks:
  • DBMS_SQL.PARSE() could not handle CLOB argument
  • A REF CURSOR can not be converted to a DBMS_SQL cursor and vice versa to support interoperability
  • DBMS_SQL did not supports the full range of data types (including collections and object types)
  • DBMS_SQL did not allows bulk binds using user-define (sic) collection types
A Simple example to show how DBMS_SQL was used to take care of long strings : Example 2:
DECLARE
   vara           VARCHAR2 (32767);
   varb           VARCHAR2 (32767);
   ln_cursor   NUMBER;
   ln_result   NUMBER;
   ln_sql_id   NUMBER           := 1;
BEGIN
   ln_cursor                  := DBMS_SQL.open_cursor;
   
   vara                          := 'create table testa( a number(10),';
   -- to make length  32 k
   while length(vara) <32000 
   loop
   vara := vara || chr(10) || '--comment';
   end loop;
   
   varb                          := ' b number(10))';
   -- to make length  32 k
   while length(varb) <32000 loop
   varb := varb || chr(10) || '--comment';
   end loop;
   dbms_output.put_line (length(vara)||'and'||length(varb));
   DBMS_SQL.parse (ln_cursor, vara ||chr(10)|| varb, DBMS_SQL.native);
   ln_result                  := DBMS_SQL.EXECUTE (ln_cursor);
   DBMS_SQL.close_cursor (ln_cursor);
END;

CLOB argument in Oracle 11g

Oracle Database 11g removes DBMS_SQL limitations restrictions to make the support of dynamic SQL from PL/SQL functionally complete. Lets see it through an Example. Example 3: The only difference in Example 3 as compared to Example 2 is Use of CLOB for the declaration of vara variable.
DECLARE
   vara        CLOB;
   ln_cursor   NUMBER;
   ln_result   NUMBER;
   ln_sql_id   NUMBER           := 1;
BEGIN
   ln_cursor                  := DBMS_SQL.open_cursor;
   
   vara                          := 'create table testa( a number(10))';
   -- to make length  32 k
   while length(vara) <70000 
   loop
   vara := vara || chr(10) || '--comment';
   end loop;
   
   
   dbms_output.put_line (length(vara));
   DBMS_SQL.parse (ln_cursor, vara, DBMS_SQL.native);
   ln_result                  := DBMS_SQL.EXECUTE (ln_cursor);
   DBMS_SQL.close_cursor (ln_cursor);
END;
Now Both Native Dynamic SQL and DBMS_SQL support SQL strings stored in CLOBs. But using DBMS_SQL has an overload of PARSE that accepts a collection of SQL string fragments. This is not ideal and the CLOB implementation in EXECUTE IMMEDIATE solves any issues we might have had with the previous alternatives. Example 4:
DECLARE
   vara           CLOB;
   
BEGIN
   vara                          := 'create table testa( a number(10))';
   -- to make length  64k k
   while length(vara) <70000 
   loop
   vara := vara || chr(10) || '--comment';
   end loop;
   
   dbms_output.put_line (length(vara));
   EXECUTE IMMEDIATE vara;
   
END; 
So now don’t worry about the size of strings, Oracle 11g has solved the limitations we had for Dynamic SQL executions.

Compound Triggers in Oracle 11g – Tutorial with example

$
0
0
Compound Triggers in Oracle 11gIn Oracle 11g, the concept of compound trigger was introduced. A compound trigger is a single trigger on a table that enables you to specify actions for each of four timing points:
  1. Before the firing statement
  2. Before each row that the firing statement affects
  3. After each row that the firing statement affects
  4. After the firing statement
With the compound trigger, both the statement-level and row-level action can be put up in a single trigger. Plus there is an added advantage: it allows sharing of common state between all the trigger-points using variable. This is because compound trigger in oracle 11g has a declarative section where one can declare variable to be used within trigger. This common state is established at the start of triggering statement and is destroyed after completion of trigger (regardless of trigger being in error or not). If same had to be done without compound-trigger, it might have been required to share data using packages.

When to use Compound Triggers

The compound trigger is useful when you want to accumulate facts that characterize the “for each row” changes and then act on them as a body at “after statement” time. Two popular reasons to use compound trigger are:
  1. To accumulate rows for bulk-insertion. We will later see an example for this.
  2. To avoid the infamous ORA-04091: mutating-table error.

Details of Syntax

CREATE OR REPLACE TRIGGER compound_trigger_name
FOR [INSERT|DELETE]UPDATE [OF column] ON table
COMPOUND TRIGGER
   -- Declarative Section (optional)
   -- Variables declared here have firing-statement duration.
     
     --Executed before DML statement
     BEFORE STATEMENT IS
     BEGIN
       NULL;
     END BEFORE STATEMENT;
   
     --Executed before each row change- :NEW, :OLD are available
     BEFORE EACH ROW IS
     BEGIN
       NULL;
     END BEFORE EACH ROW;
   
     --Executed aftereach row change- :NEW, :OLD are available
     AFTER EACH ROW IS
     BEGIN
       NULL;
     END AFTER EACH ROW;
   
     --Executed after DML statement
     AFTER STATEMENT IS
     BEGIN
       NULL;
     END AFTER STATEMENT;

END compound_trigger_name;
Note the ‘COMPOUND TRIGGER’ keyword above.

Some Restriction/Catches to note

  1. The body of a compound trigger must be a compound trigger block.
  2. A compound trigger must be a DML trigger.
  3. A compound trigger must be defined on either a table or a view.
  4. The declarative part cannot include PRAGMA AUTONOMOUS_TRANSACTION.
  5. A compound trigger body cannot have an initialization block; therefore, it cannot have an exception section. This is not a problem, because the BEFORE STATEMENT section always executes exactly once before any other timing-point section executes.
  6. An exception that occurs in one section must be handled in that section. It cannot transfer control to another section.
  7. If a section includes a GOTO statement, the target of the GOTO statement must be in the same section.
  8. OLD, :NEW, and :PARENT cannot appear in the declarative part, the BEFORE STATEMENT section, or the AFTER STATEMENT section.
  9. Only the BEFORE EACH ROW section can change the value of :NEW.
  10. If, after the compound trigger fires, the triggering statement rolls back due to a DML exception:
    • Local variables declared in the compound trigger sections are re-initialized, and any values computed thus far are lost.
    • Side effects from firing the compound trigger are not rolled back.
  11. The firing order of compound triggers is not guaranteed. Their firing can be interleaved with the firing of simple triggers.
  12. If compound triggers are ordered using the FOLLOWS option, and if the target of FOLLOWS does not contain the corresponding section as source code, the ordering is ignored.

Example: Using Compound Triggers in Table Auditing

Hopefully this example with make things more clear. Lets create a compound trigger for auditing a large table called ’employees’. Any changes made in any field of ’employees’ table needs to be logged in as a separate row in audit table ‘aud_empl’. Since each row update in employees table needs to make multiple inserts in the audit table, we should consider using a compound trigger so that batching of inserts can be performed. But before that we need to create our Tables:
--Target Table
CREATE TABLE employees(
    emp_id  varchar2(50) NOT NULL PRIMARY KEY,
    name    varchar2(50) NOT NULL, 
    salary  number NOT NULL
);

--Audit Table
CREATE TABLE aud_emp(
    upd_by    varchar2(50) NOT NULL, 
    upd_dt    date NOT NULL,
    field     varchar2(50) NOT NULL, 
    old_value varchar2(50) NOT NULL,
    new_value varchar2(50) NOT NULL);
Now the trigger… On update of each row instead of performing an insert operation for each field, we store (buffer) the required attributes in a Arrays of type aud_emp. Once a threshold is reached (say 1000 records), we flush the buffered data into audit table and reset the counter for further buffering. And at last, as part of AFTER STATEMENT we flush any remaining data left in buffer.
--Trigger
CREATE OR REPLACE TRIGGER aud_emp
FOR INSERT OR UPDATE
ON employees
COMPOUND TRIGGER
  
  TYPE t_emp_changes       IS TABLE OF aud_emp%ROWTYPE INDEX BY SIMPLE_INTEGER;
  v_emp_changes            t_emp_changes;
  
  v_index                  SIMPLE_INTEGER       := 0;
  v_threshhold    CONSTANT SIMPLE_INTEGER       := 1000; --maximum number of rows to write in one go.
  v_user          VARCHAR2(50); --logged in user
  
  PROCEDURE flush_logs
  IS
    v_updates       CONSTANT SIMPLE_INTEGER := v_emp_changes.count();
  BEGIN

    FORALL v_count IN 1..v_updates
        INSERT INTO aud_emp
             VALUES v_emp_changes(v_count);

    v_emp_changes.delete();
    v_index := 0; --resetting threshold for next bulk-insert.

  END flush_logs;

  AFTER EACH ROW
  IS
  BEGIN
        
    IF INSERTING THEN
        v_index := v_index + 1;
        v_emp_changes(v_index).upd_dt       := SYSDATE;
        v_emp_changes(v_index).upd_by       := SYS_CONTEXT ('USERENV', 'SESSION_USER');
        v_emp_changes(v_index).emp_id       := :NEW.emp_id;
        v_emp_changes(v_index).action       := 'Create';
        v_emp_changes(v_index).field        := '*';
        v_emp_changes(v_index).from_value   := 'NULL';
        v_emp_changes(v_index).to_value     := '*';

    ELSIF UPDATING THEN
        IF (   (:OLD.EMP_ID <> :NEW.EMP_ID)
                OR (:OLD.EMP_ID IS     NULL AND :NEW.EMP_ID IS NOT NULL)
                OR (:OLD.EMP_ID IS NOT NULL AND :NEW.EMP_ID IS     NULL)
                  )
             THEN
                v_index := v_index + 1;
                v_emp_changes(v_index).upd_dt       := SYSDATE;
                v_emp_changes(v_index).upd_by       := SYS_CONTEXT ('USERENV', 'SESSION_USER');
                v_emp_changes(v_index).emp_id       := :NEW.emp_id;
                v_emp_changes(v_index).field        := 'EMP_ID';
                v_emp_changes(v_index).from_value   := to_char(:OLD.EMP_ID);
                v_emp_changes(v_index).to_value     := to_char(:NEW.EMP_ID);
                v_emp_changes(v_index).action       := 'Update';
          END IF;
        
        IF (   (:OLD.NAME <> :NEW.NAME)
                OR (:OLD.NAME IS     NULL AND :NEW.NAME IS NOT NULL)
                OR (:OLD.NAME IS NOT NULL AND :NEW.NAME IS     NULL)
                  )
             THEN
                v_index := v_index + 1;
                v_emp_changes(v_index).upd_dt       := SYSDATE;
                v_emp_changes(v_index).upd_by       := SYS_CONTEXT ('USERENV', 'SESSION_USER');
                v_emp_changes(v_index).emp_id       := :NEW.emp_id;
                v_emp_changes(v_index).field        := 'NAME';
                v_emp_changes(v_index).from_value   := to_char(:OLD.NAME);
                v_emp_changes(v_index).to_value     := to_char(:NEW.NAME);
                v_emp_changes(v_index).action       := 'Update';
          END IF;
                       
        IF (   (:OLD.SALARY <> :NEW.SALARY)
                OR (:OLD.SALARY IS     NULL AND :NEW.SALARY IS NOT NULL)
                OR (:OLD.SALARY IS NOT NULL AND :NEW.SALARY IS     NULL)
                  )
             THEN
                v_index := v_index + 1;
                v_emp_changes(v_index).upd_dt      := SYSDATE;
                v_emp_changes(v_index).upd_by      := SYS_CONTEXT ('USERENV', 'SESSION_USER');
                v_emp_changes(v_index).emp_id      := :NEW.emp_id;
                v_emp_changes(v_index).field       := 'SALARY';
                v_emp_changes(v_index).from_value  := to_char(:OLD.SALARY);
                v_emp_changes(v_index).to_value    := to_char(:NEW.SALARY);
                v_emp_changes(v_index).action      := 'Update';
          END IF;
                       
    END IF;

    IF v_index >= v_threshhold THEN
      flush_logs();
    END IF;

   END AFTER EACH ROW;

  -- AFTER STATEMENT Section:
  AFTER STATEMENT IS
  BEGIN
     flush_logs();
  END AFTER STATEMENT;

END aud_emp;
/

INSERT INTO employees VALUES (1, 'emp1', 10000);
INSERT INTO employees VALUES (2, 'emp2', 20000);
INSERT INTO employees VALUES (3, 'emp3', 16000);

UPDATE employees 
   SET salary = 2000
 WHERE salary > 15000;

SELECT * FROM aud_emp;
Result:
EMP_ID,UPD_BY,UPD_DT,ACTION,FIELD,FROM_VALUE,TO_VALUE
1,Aditya,1/22/2014 10:59:33 AM,Create,*,NULL,*
2,Aditya,1/22/2014 10:59:34 AM,Create,*,NULL,*
3,Aditya,1/22/2014 10:59:35 AM,Create,*,NULL,*
2,Aditya,1/22/2014 10:59:42 AM,Update,SALARY,20000,2000
3,Aditya,1/22/2014 10:59:42 AM,Update,SALARY,16000,2000
Now any changes in any field of employees will to be written in aud_emp table. A beauty of this approach is we were able to access same data ‘v_emp_changes’ between statement and row triggering events. With this in mind, one can see that it make sense to move v_emp_changes(v_index).upd_by := SYS_CONTEXT ('USERENV', 'SESSION_USER'); inside declarative(or BEFORE STATEMENT if complex computation) section as a pre-processing step. To do so, v_user variable declared in trigger body can be used and assigned value of logged in user in the declarative section itself. So that same computation is not made during after-each-row section, and is computed and stored in a variable just once before row-level execution begins.
--declarative section
v_user          VARCHAR2(50) := SYS_CONTEXT ('USERENV', 'SESSION_USER');
Similarly any such pre-processing if required can be performed on that source table (mutating table), doing so will avoid any possible mutating-error. For e.g., consider the same example with another restriction, “Any update of salary should be such that it is not less than 1/12th of maximum salary of any employee, or else an error is raised”. To do this, it will be needed to get the maximum value of salary in the ’employees’ table, and such calculation can be made in BEFORE STATEMENT section and stored in variable. Hope that helped to have a better understanding of Compound Triggers in Oracle. The End :-)

Auditing DML changes in Oracle

$
0
0
auditing sql in oracleWe are often faced with a situation when every DML change (Inserts/Updates/Deletes) made in Oracle/SQL tables must be audited. Banking Softwares and other similar applications have a strict requirement to maintain the audit trail of every single change made to the database. The DML changes must be audited irrespective of whether it was made from the Front End, during a release, or directly by a production support person while serving a production ticket. Ever wondered how an audit trail of such large numbers tables in your database can be created. Especially when your application is ever-changing with new columns getting added, dropped or modified often. Triggers in oracle often come handy when fulfilling audit requirements for your database. An audit trigger can be created on the table which will compare the old and new values of all the columns and in case of a difference will log the old record into an audit table. The audit table will have a similar structure to the main table with 3 additional columns AUDIT_BY, AUDIT_AT and AUDIT_ACTION. Triggers will ensure that the audit trail is maintained irrespective of from where the database change was initiated. However creating such large number of audit tables and triggers manually can be a huge effort. In this article I will demonstrate how easily we can create audit tables and triggers in oracle for database of any size very easily and with very less effort.

Step 1 – Create some tables

Create some sample tables for which you would like to maintain the audit trail.
CREATE TABLE EMPLOYEE
(
   EID     NUMBER,
   ENAME   VARCHAR2 (40)
);

CREATE TABLE DEPARTMENT
(
   DID     NUMBER,
   DNAME   VARCHAR2 (40)
);

CREATE TABLE SALARY
(
   EID   	NUMBER,
   SALARY	NUMBER
);

Step 2 – Create an exclude table

There will be always some tables which we would like to exclude from the audit. For example if the table is very huge, contains blob or images, or if the table is rarely modified we might not want to audit it. The exclude table will contain a list of such table which we would like to exclude from the audit.
CREATE TABLE EXAUDIT
(
   TNAME VARCHAR2 (30) NOT NULL
);
In our example let us assume that we want to exclude the department table from the audit. We simply make an entry of this table in our exclude table.
INSERT INTO EXAUDIT (TNAME)
     VALUES ('DEPARTMENT');

Step 3 – Create audit tables

Now comes the interesting part. We want to create audit tables that will hold the audit trail of all the tables in our database. This can be achieved with a simple procedure like below.
CREATE OR REPLACE PROCEDURE create_audit_tables (table_owner VARCHAR2)
IS
   CURSOR c_tables (
      table_owner VARCHAR2)
   IS
SELECT ot.owner AS owner, ot.table_name AS table_name
        FROM all_tables ot
       WHERE     ot.owner = table_owner
             AND ot.table_name NOT LIKE 'AUDIT_%'
             AND ot.table_name <> 'EXAUDIT'
             AND NOT EXISTS
                    (SELECT 1
                       FROM EXAUDIT efa
                      WHERE ot.table_name = efa.tname)
             AND NOT EXISTS
                        (SELECT 1
                           FROM all_tables at
                          WHERE at.table_name = 'AUDIT_'||ot.table_name);

   v_sql     VARCHAR2 (8000);
   v_count   NUMBER := 0;
   v_aud     VARCHAR2 (30);
BEGIN
   FOR r_table IN c_tables (table_owner)
   LOOP
      BEGIN
         v_aud := 'AUDIT_'||r_table.table_name;
         v_sql :=
               'create table '
            || v_aud
            || ' as select * from '
            || r_table.owner
            || '.'
            || r_table.table_name
            || ' where 0 = 1';

         DBMS_OUTPUT.put_line ('Info: ' || v_sql);

         EXECUTE IMMEDIATE v_sql;

         v_sql :=
               'alter table '
            || v_aud
            || ' add ( AUDIT_ACTION char(1), AUDIT_BY varchar2(50), AUDIT_AT TIMESTAMP)';

         EXECUTE IMMEDIATE v_sql;

         v_count := c_tables%ROWCOUNT;
      EXCEPTION
         WHEN OTHERS
         THEN
            DBMS_OUTPUT.put_line (
                  'Failed to create table '
               || v_aud
               || ' due to '
               || SQLERRM);
      END;
   END LOOP;

   IF v_count = 0
   THEN
      DBMS_OUTPUT.put_line ('No audit tables created');
   ELSE
      DBMS_OUTPUT.put_line (v_count || ' audit tables created.');
   END IF;
END;
/
After the above procedure is created execute it by passing the schema name (owner) of the schema where your main tables were created.
execute create_audit_tables('SCHEMANAME');
This will create audit tables corresponding to all main tables and with the additional columns like audit_on,audit_by and audit_action. The tables in the exclude table will be excluded.

Step 4 – Create audit triggers

I will first create a small helper function that will give me a comma separated list of columns of a given table (with a prefix if required)
create or replace FUNCTION get_columns_for_table (
     table_owner   VARCHAR2,
     t_name   VARCHAR2,
     prefix  VARCHAR2
  ) RETURN  CLOB
  IS
     v_text CLOB;
  BEGIN
     FOR getrec IN (SELECT column_name
                      FROM all_tab_columns
                     WHERE table_name = t_name
        AND owner = table_owner
        AND data_type<>'BLOB')
     LOOP
       v_text := v_text
          || ','
          || prefix
          || getrec.column_name
          || CHR (10)
          || '                             ';
     END LOOP;

     RETURN ltrim(v_text,',');
  END;
Next create a helper function that will give us a comparison between the columns in case of table updates
create or replace function get_column_comparasion (
     table_owner   VARCHAR2,
     t_name   VARCHAR2
  ) RETURN CLOB
  IS
    v_text CLOB;
  BEGIN
    FOR getrec IN (SELECT column_name
                     FROM all_tab_columns
                    WHERE table_name = t_name
                      AND owner = table_owner
                      AND data_type<>'BLOB')
   LOOP
      v_text := v_text
         || ' or( (:old.'
         || getrec.column_name
         || ' <> :new.'
         || getrec.column_name
         || ') or (:old.'
         || getrec.column_name
         || ' IS NULL and  :new.'
         || getrec.column_name
         || ' IS NOT NULL)  or (:old.'
         || getrec.column_name
         || ' IS NOT NULL and  :new.'
         || getrec.column_name
         || ' IS NULL))'
         || CHR (10)
         || '                ';
   END LOOP;

   v_text := LTRIM (v_text, ' or');
   RETURN v_text;
  END;
Next create the procedure that will create our audit triggers
CREATE OR REPLACE PROCEDURE create_audit_triggers (table_owner VARCHAR2)
IS
   CURSOR c_tab_inc (
      table_owner VARCHAR2)
   IS
      SELECT ot.owner AS owner, ot.table_name AS table_name
        FROM all_tables ot
       WHERE     ot.owner = table_owner
             AND ot.table_name NOT LIKE 'AUDIT_%'
             AND ot.table_name <> 'EXAUDIT'
             AND ot.table_name NOT IN (SELECT tname FROM EXAUDIT);

   v_query   VARCHAR2 (32767);
   v_count   NUMBER := 0;
BEGIN
   FOR r_tab_inc IN c_tab_inc (table_owner)
   LOOP
      BEGIN

         v_query :=
               'CREATE OR REPLACE TRIGGER TRIGGER_'
            || r_tab_inc.table_name
            || ' AFTER INSERT OR UPDATE OR DELETE ON '
            || r_tab_inc.owner
            || '.'
            || r_tab_inc.table_name
            || ' FOR EACH ROW'
            || CHR (10)
            || 'DECLARE '
            || CHR (10)
            || ' v_user varchar2(30):=null;'
            || CHR (10)
            || ' v_action varchar2(15);'
            || CHR (10)
            || 'BEGIN'
            || CHR (10)
            || '   SELECT SYS_CONTEXT (''USERENV'', ''session_user'') session_user'
            || CHR (10)
            || '   INTO v_user'
            || CHR (10)
            || '   FROM DUAL;'
            || CHR (10)
            || ' if inserting then '
            || CHR (10)
            || ' v_action:=''INSERT'';'
            || CHR (10)
            || '      insert into AUDIT_'
            || r_tab_inc.table_name
            || '('
            || get_columns_for_table (r_tab_inc.owner,
                                      r_tab_inc.table_name,
                                      NULL)
            || '      ,AUDIT_ACTION,AUDIT_BY,AUDIT_AT)'
            || CHR (10)
            || '      values ('
            || get_columns_for_table (r_tab_inc.owner,
                                      r_tab_inc.table_name,
                                      ':new.')
            || '      ,''I'',v_user,SYSDATE);'
            || CHR (10)
            || ' elsif updating then '
            || CHR (10)
            || ' v_action:=''UPDATE'';'
            || CHR (10)
            || '   if '
            || get_column_comparasion (r_tab_inc.owner, r_tab_inc.table_name)
            || ' then '
            || CHR (10)
            || '      insert into AUDIT_'
            || r_tab_inc.table_name
            || '('
            || get_columns_for_table (r_tab_inc.owner,
                                      r_tab_inc.table_name,
                                      NULL)
            || '      ,AUDIT_ACTION,AUDIT_BY,AUDIT_AT)'
            || CHR (10)
            || '      values ('
            || get_columns_for_table (r_tab_inc.owner,
                                      r_tab_inc.table_name,
                                      ':new.')
            || '      ,''U'',v_user,SYSDATE);'
            || CHR (10)
            || '   end if;'
            || ' elsif deleting then'
            || CHR (10)
            || ' v_action:=''DELETING'';'
            || CHR (10)
            || '      insert into AUDIT_'
            || r_tab_inc.table_name
            || '('
            || get_columns_for_table (r_tab_inc.owner,
                                      r_tab_inc.table_name,
                                      NULL)
            || '      ,AUDIT_ACTION,AUDIT_BY,AUDIT_AT)'
            || CHR (10)
            || '      values ('
            || get_columns_for_table (r_tab_inc.owner,
                                      r_tab_inc.table_name,
                                      ':old.')
            || '      ,''D'',v_user,SYSDATE);'
            || CHR (10)
            || '   end if;'
            || CHR (10)
            || 'END;';

         DBMS_OUTPUT.put_line (
               'CREATE TRIGGER '
            || REPLACE (r_tab_inc.table_name, 'TABLE_', 'TRIGGER_'));

         EXECUTE IMMEDIATE v_query;

         DBMS_OUTPUT.put_line (
               'Audit trigger '
            || REPLACE (r_tab_inc.table_name, 'TABLE_', 'TRIGGER_')
            || ' created.');

         v_count := c_tab_inc%ROWCOUNT;
      EXCEPTION
         WHEN OTHERS
         THEN
            DBMS_OUTPUT.put_line (
                  'Failed to create audit trigger for '
               || r_tab_inc.owner
               || '.'
               || r_tab_inc.table_name
               || ' due to '
               || SQLERRM);
      END;
   END LOOP;

   IF v_count = 0
   THEN
      DBMS_OUTPUT.put_line ('No audit triggers created');
   END IF;
END;
Finally execute the procedure. This will create all the audit triggers.
EXECUTE CREATE_AUDIT_TRIGGERS('SCHEMANAME');

Step 5 – Test the auditing

Now execute a few DML scripts and notice that all changes made to our main tables get audited with appropriate action in the audit tables. Changes to department table will not be audited as we have excluded it.
insert into employee values(1,'John');

insert into employee values(2,'Smith');

insert into department values(1,'Sales');

insert into department values(2,'Purchase');

insert into salary values(1,5000);

insert into salary values(2,10000);

delete from employee where eid = 1;

update employee set ename = 'Raj' where eid = 2;
All tables will have a primary key which never changes. Using the primary key we can query our audit tables and get the entire audit trail when required. Instead of session user we can also set the user from the middle tier in the SYS_CONTEXT. Here I demonstrated how with few simple procedures you can fulfil the audit requirement of your application. The concepts and scripts here are very small but quite powerful and can be used to create audit trail for any number of tables in your database.
Viewing all 25 articles
Browse latest View live