Wednesday, December 29, 2010

Oracle : DML Error Logging in Oracle 10g

Source : http://www.oracle-base.com/articles/10g/DmlErrorLogging_10gR2.php

One of the nice feature of Oracle 10G

DML Error Logging in Oracle 10g Database Release 2

By default, when a DML statement fails the whole statement is rolled back, regardless of how many rows were processed successfully before the error was detected. In the past, the only way around this problem was to process each row individually, preferably with a bulk operation using a FORALL loop with the SAVE EXCEPTIONS clause. In Oracle 10g Database Release 2, the DML error logging feature has been introduced to solve this problem. Adding the appropriate LOG ERRORS clause on to most INSERT, UPDATE, MERGE and DELETE statements enables the operations to complete, regardless of errors. This article presents an overview of the DML error logging functionality, with examples of each type of DML statement.

Syntax

The syntax for the error logging clause is the same for INSERT, UPDATE, MERGE and DELETE statements.

LOG ERRORS [INTO [schema.]table] [('simple_expression')] [REJECT LIMIT integer|UNLIMITED]

The optional INTO clause allows you to specify the name of the error logging table. If you omit this clause, the the first 25 characters of the base table name are used along with the "ERR$_" prefix.

The
simple_expression is used to specify a tag that makes the errors easier to identify. This might be a string or any function whose result is converted to a string.

The
REJECT LIMIT is used to specify the maximum number of errors before the statement fails. The default value is 0 and the maximum values is the keyword UNLIMITED. For parallel DML operations, the reject limit is applied to each parallel server.

Restrictions

The DML error logging functionality is not invoked when:

  • Deferred constraints are violated.
  • Direct-path INSERT or MERGE operations raise unique constraint or index violations.
  • UPDATE or MERGE operations raise a unique constraint or index violation.

In addition, the tracking of errors in LONG, LOB and object types is not supported, although a table containing these columns can be the target of error logging.

Sample Schema

This following code creates and populates the tables necessary to run the example code in this article.

-- Create and populate a source table.

CREATE TABLE source (

id NUMBER(10) NOT NULL,

code VARCHAR2(10),

description VARCHAR2(50),

CONSTRAINT source_pk PRIMARY KEY (id)

);


 

DECLARE

TYPE t_tab IS TABLE OF source%ROWTYPE;

l_tab t_tab := t_tab();

BEGIN

FOR i IN 1 .. 100000 LOOP

l_tab.extend;

l_tab(l_tab.last).id := i;

l_tab(l_tab.last).code := TO_CHAR(i);

l_tab(l_tab.last).description := 'Description for ' || TO_CHAR(i);

END LOOP;


 

-- For a possible error condition.

l_tab(1000).code := NULL;

l_tab(10000).code := NULL;


 

FORALL i IN l_tab.first .. l_tab.last

INSERT INTO source VALUES l_tab(i);


 

COMMIT;

END;

/


 

EXEC DBMS_STATS.gather_table_stats(USER, 'source', cascade => TRUE);


 

-- Create a destination table.

CREATE TABLE dest (

id NUMBER(10) NOT NULL,

code VARCHAR2(10) NOT NULL,

description VARCHAR2(50),

CONSTRAINT dest_pk PRIMARY KEY (id)

);


 

-- Create a dependant of the destination table.

CREATE TABLE dest_child (

id NUMBER,

dest_id NUMBER,

CONSTRAINT child_pk PRIMARY KEY (id),

CONSTRAINT dest_child_dest_fk FOREIGN KEY (dest_id) REFERENCES dest(id)

);

Notice that the CODE column is optional in the SOURCE table and mandatory in the DEST table.

Once the basic tables are in place we can create a table to hold the DML error logs for the
DEST. A log table must be created for every base table that requires the DML error logging functionality. This can be done manually or with the CREATE_ERROR_LOG procedure in the DBMS_ERRLOG package, as shown below.

-- Create the error logging table.

BEGIN

DBMS_ERRLOG.create_error_log (dml_table_name => 'dest');

END;

/


 

PL/SQL procedure successfully completed.


 

SQL>

The owner, name and tablespace of the log table can be specified, but by default it is created in the current schema, in the default tablespace with a name that matches the first 25 characters of the base table with the "ERR$_" prefix.

SELECT owner, table_name, tablespace_name

FROM all_tables

WHERE owner = 'TEST';


 

OWNER TABLE_NAME TABLESPACE_NAME

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

TEST DEST USERS

TEST DEST_CHILD USERS

TEST ERR$_DEST USERS

TEST SOURCE USERS


 

4 rows selected.


 

SQL>

The structure of the log table includes maximum length and datatype independent versions of all available columns from the base table, as seen below.

SQL> DESC err$_dest

Name Null? Type

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

ORA_ERR_NUMBER$ NUMBER

ORA_ERR_MESG$ VARCHAR2(2000)

ORA_ERR_ROWID$ ROWID

ORA_ERR_OPTYP$ VARCHAR2(2)

ORA_ERR_TAG$ VARCHAR2(2000)

ID VARCHAR2(4000)

CODE VARCHAR2(4000)

DESCRIPTION VARCHAR2(4000)


 

SQL>

Insert

When we built the sample schema we noted that the CODE column is optional in the SOURCE table, but mandatory in th DEST table. When we populated the SOURCE table we set the code to NULL for two of the rows. If we try to copy the data from the SOURCE table to the DEST table we get the following result.

INSERT INTO dest

SELECT *

FROM source;


 

SELECT *

*

ERROR at line 2:

ORA-01400: cannot insert NULL into ("TEST"."DEST"."CODE")


 


 

SQL>

The failure causes the whole insert to roll back, regardless of how many rows were inserted successfully. Adding the DML error logging clause allows us to complete the insert of the valid rows.

INSERT INTO dest

SELECT *

FROM source

LOG ERRORS INTO err$_dest ('INSERT') REJECT LIMIT UNLIMITED;


 

99998 rows created.


 

SQL>

The rows that failed during the insert are stored in the ERR$_DEST table, along with the reason for the failure.

COLUMN ora_err_mesg$ FORMAT A70

SELECT ora_err_number$, ora_err_mesg$

FROM err$_dest

WHERE ora_err_tag$ = 'INSERT';


 

ORA_ERR_NUMBER$ ORA_ERR_MESG$

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

1400 ORA-01400: cannot insert NULL into ("TEST"."DEST"."CODE")

1400 ORA-01400: cannot insert NULL into ("TEST"."DEST"."CODE")


 

2 rows selected.


 

SQL>

Update

The following code attempts to update the CODE column for 10 rows, setting it to itself for 8 rows and to the value NULL for 2 rows.

UPDATE dest

SET code = DECODE(id, 9, NULL, 10, NULL, code)

WHERE id BETWEEN 1 AND 10;

*

ERROR at line 2:

ORA-01407: cannot update ("TEST"."DEST"."CODE") to NULL


 


 

SQL>

As expected, the statement fails because the CODE column is mandatory. Adding the DML error logging clause allows us to complete the update of the valid rows.

UPDATE dest

SET code = DECODE(id, 9, NULL, 10, NULL, code)

WHERE id BETWEEN 1 AND 10

LOG ERRORS INTO err$_dest ('UPDATE') REJECT LIMIT UNLIMITED;


 

8 rows updated.


 

SQL>

The rows that failed during the update are stored in the ERR$_DEST table, along with the reason for the failure.

COLUMN ora_err_mesg$ FORMAT A70

SELECT ora_err_number$, ora_err_mesg$

FROM err$_dest

WHERE ora_err_tag$ = 'UPDATE';


 

ORA_ERR_NUMBER$ ORA_ERR_MESG$

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

1400 ORA-01400: cannot insert NULL into ("TEST"."DEST"."CODE")

1400 ORA-01400: cannot insert NULL into ("TEST"."DEST"."CODE")


 

2 rows selected.


 

SQL>

Merge

The following code deletes some of the rows from the DEST table, then attempts to merge the data from the SOURCE table into the DEST table.

DELETE FROM dest

WHERE id > 50000;


 

MERGE INTO dest a

USING source b

ON (a.id = b.id)

WHEN MATCHED THEN

UPDATE SET a.code = b.code,

a.description = b.description

WHEN NOT MATCHED THEN

INSERT (id, code, description)

VALUES (b.id, b.code, b.description);

*

ERROR at line 9:

ORA-01400: cannot insert NULL into ("TEST"."DEST"."CODE")


 


 

SQL>

As expected, the merge operation fails and rolls back. Adding the DML error logging clause allows the merge operation to complete.

MERGE INTO dest a

USING source b

ON (a.id = b.id)

WHEN MATCHED THEN

UPDATE SET a.code = b.code,

a.description = b.description

WHEN NOT MATCHED THEN

INSERT (id, code, description)

VALUES (b.id, b.code, b.description)

LOG ERRORS INTO err$_dest ('MERGE') REJECT LIMIT UNLIMITED;


 

99998 rows merged.


 

SQL>

The rows that failed during the update are stored in the ERR$_DEST table, along with the reason for the failure.

COLUMN ora_err_mesg$ FORMAT A70

SELECT ora_err_number$, ora_err_mesg$

FROM err$_dest

WHERE ora_err_tag$ = 'MERGE';


 

ORA_ERR_NUMBER$ ORA_ERR_MESG$

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

1400 ORA-01400: cannot insert NULL into ("TEST"."DEST"."CODE")

1400 ORA-01400: cannot insert NULL into ("TEST"."DEST"."CODE")


 

2 rows selected.


 

SQL>

Delete

The DEST_CHILD table has a foreign key to the DEST table, so if we add some data to it would would expect an error if we tried to delete the parent rows from the DEST table.

INSERT INTO dest_child (id, dest_id) VALUES (1, 100);

INSERT INTO dest_child (id, dest_id) VALUES (2, 101);

With the child data in place we ca attempt to delete th data from the DEST table.

DELETE FROM dest;

*

ERROR at line 1:

ORA-02292: integrity constraint (TEST.DEST_CHILD_DEST_FK) violated - child record found


 


 

SQL>

As expected, the delete operation fails. Adding the DML error logging clause allows the delete operation to complete.

DELETE FROM dest

LOG ERRORS INTO err$_dest ('DELETE') REJECT LIMIT UNLIMITED;


 

99996 rows deleted.


 

SQL>

The rows that failed during the delete operation are stored in the ERR$_DEST table, along with the reason for the failure.

COLUMN ora_err_mesg$ FORMAT A69

SELECT ora_err_number$, ora_err_mesg$

FROM err$_dest

WHERE ora_err_tag$ = 'DELETE';


 

ORA_ERR_NUMBER$ ORA_ERR_MESG$

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

2292 ORA-02292: integrity constraint (TEST.DEST_CHILD_DEST_FK) violated -

child record found


 

2292 ORA-02292: integrity constraint (TEST.DEST_CHILD_DEST_FK) violated -

child record found


 


 

2 rows selected.


 

SQL>

Tuesday, November 16, 2010

VBA :Macro to Download Email Attachments

Start Outlook à
Tools à Macro à Visual Basic Editor.

Add a new code module by choosing Insert > Module and add the following code. Compile the Macro and run.


 

Sub DownloadAttachments()


Dim ns As
NameSpace


Dim Inbox As MAPIFolder


Dim Subfolder As MAPIFolder


Dim Item As
Object


Dim Atmt As Attachment


Dim FileName As
String


Dim Localfolder As
String


Dim SubfolderName As
String


 


Dim i As
Integer


Dim j As
Integer


 


'***************************


' This Macro is coded to downlaod the files only from the folders under the INBOX.


' Apprently you could change ns.GetDefaultFolder(olFolderInbox) argument to any other folder and try.

' The NameSpace is the object that gives you access to all Outlook's folders.


' In Outlook there is only one and it is called "MAPI" which is an acronym for Messaging Application Programming

'    Interface.


'***************************


On
Error
GoTo GetAttachments_err


 

Localfolder = "C:\Email Attachments\"

SubfolderName = "AppWorx"
'Configure your own folder name which is under your INBOX.


 

ns = GetNamespace("MAPI")

Inbox = ns.GetDefaultFolder(olFolderInbox) ''Change the argument to any other folder.

Subfolder = Inbox.Folders(SubfolderName)

i = 0


 


If Subfolder.Items.Count = 0 Then

MsgBox("There are no messages in the folder." _

, vbInformation, "Nothing Found")


Exit
Sub


End
If


 


If Subfolder.Items.Count > 0 Then

j = j + 1


For
Each Item In Subfolder.Items


For
Each Atmt In Item.Attachments


If LCase(Right(Atmt.FileName, 4)) = ".csv"
Then 'change your filter logi here

FileName = Localfolder & Atmt.FileName

Atmt.SaveAsFile(FileName)

i = i + 1


End
If


Next Atmt


Next Item


End
If


 


 


If i > 0 Then

varResponse = MsgBox("Downloaded " & i & " files." _

& vbCrLf & "Saved @" & Localfolder & " folder." _

& vbCrLf & vbCrLf & "Would you like to view the files now?" _

, vbQuestion + vbYesNo, "Finished!")


If varResponse = vbYes Then

Shell("Explorer.exe /e, " & Localfolder, vbNormalFocus)


End
If


Else

MsgBox("I didn't find any attached files in your mail.", vbInformation, _


"Finished!")


End
If


 

GetAttachments_exit:

Atmt = Nothing

Item = Nothing

ns = Nothing


Exit
Sub


 

GetAttachments_err:

MsgBox("An unexpected error has occurred. @" & j & "Email record" & Err.Number _

& vbCrLf & "Error Description: " & Err.Description _

, vbCritical, "Error!")


Resume GetAttachments_exit

End
Sub

Thursday, August 19, 2010

Open a web URL in Visual Basic 6.0

"ShellExecute" : Without adding Active X/COM components to the project, the simplest way to achieve this by using Windows API call.


Add the following API declaration at the form level declaration section

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Parameters :

hwnd [in, optional]

A handle to the owner window used for displaying a UI or error messages. This value can be NULL if the operation is not associated with a window.

lpOperation [in, optional]

A pointer to a null-terminated string, referred to in this case as a verb, that specifies the action to be performed:

"edit"         àLaunches an editor and opens the document for editing. If lpFile is not a document

file, the function will fail.

"explore"     à
Explores a folder specified by lpFile.

"find"         à
Initiates a search beginning in the directory specified by lpDirectory.

"open"     à
Opens the item specified by the lpFile parameter. The item can be a file or folder.

"print"         àPrints the file specified by lpFile. If lpFile is not a document file, the function fails.

"NULL"        à
Default

lpFile [in]

A pointer to a null-terminated string that specifies the file or object on which to execute the specified verb. To specify a Shell namespace object, pass the fully qualified parse name. Note that not all verbs are supported on all objects. For example, not all document types support the "print" verb. If a relative path is used for the lpDirectory parameter do not use a relative path for lpFile.

lpParameters [in, optional]

If lpFile specifies an executable file, this parameter is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL.

lpDirectory [in, optional]

A pointer to a null-terminated string that specifies the default (working) directory for the action. If this value is NULL, the current working directory is used. If a relative path is provided at lpFile, do not use a relative path for lpDirectory.

nShowCmd [in]

SW_SHOWNORMAL : Windows restores it to its original size and position.

SW_MAXIMIZE : Maximizes the specified window.

SW_MINIMIZE :Minimizes the specified window and activates the next top-level window in the z-order.

SW_SHOWMAXIMIZED : Activates the window and displays it as a maximized window.

SW_SHOWMINIMIZED : Activates the window and displays it as a minimized window.


 

For more information: Click HERE


 

Calling API function in Button_Click() event:

Private
Sub Command1_Click()


ShellExecute Me.hwnd, "open", "http://www.yahoo.com", vbNullString, "C:\", SW_SHOWNORMAL

End Sub


 

'Opens the specified URL in the Default WebBrowser.

ShellExecute 0, "open", "http://www.yahoo.com", vbNullString, vbNullString, SW_SHOWNORMAL


 

'Opens the specified URL in the specified WebBrowser.


ShellExecute 0, "open", "C:\Program Files\Mozilla Firefox\Firefox.exe", ", "http://www.yahoo.com", vbNullString, 1


 

Tuesday, August 10, 2010

Oracle: File Handler JAVA library

CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "FileHandler"

AS import java.lang.*;

import java.util.*;

import java.io.*;

import java.sql.Timestamp;


 

public class FileHandler

{


private static int SUCCESS = 1;


private static int FAILURE = 0;


 

public static void getList(String pdirectory,String pcategory)


throws SQLException


{


File path = new File( pdirectory );


String[] list = path.list();


String element;


 


for(int i = 0; i < list.length; i++)

{


element = list[i];


#sql { INSERT INTO tb_load_files (filename,processed,category)


VALUES (:element,'N', :pcategory) };

}

}


 


public static int canRead (String path) {


File myFile = new File (path);


if (myFile.canRead()) return SUCCESS; else return FAILURE;

}


 


public static int canWrite (String path) {


File myFile = new File (path);


if (myFile.canWrite()) return SUCCESS; else return FAILURE;

}


 


public static int createNewFile (String path) throws IOException {


File myFile = new File (path);


if (myFile.createNewFile()) return SUCCESS; else return FAILURE;

}


 


public static int delete (String path) {


File myFile = new File (path);


if (myFile.delete()) return SUCCESS; else return FAILURE;

}


 


public static int exists (String path) {


File myFile = new File (path);


if (myFile.exists()) return SUCCESS; else return FAILURE;

}


 


public static int isDirectory (String path) {


File myFile = new File (path);


if (myFile.isDirectory()) return SUCCESS; else return FAILURE;

}


 


public static int isFile (String path) {


File myFile = new File (path);


if (myFile.isFile()) return SUCCESS; else return FAILURE;

}


 


public static int isHidden (String path) {


File myFile = new File (path);


if (myFile.isHidden()) return SUCCESS; else return FAILURE;

}


 


public static Timestamp lastModified (String path) {


File myFile = new File (path);


return new Timestamp(myFile.lastModified());

}


 


public static long length (String path) {


File myFile = new File (path);


return myFile.length();

}


 


public static String list (String path) {


String list = "";


File myFile = new File (path);


String[] arrayList = myFile.list();


 


Arrays.sort(arrayList, String.CASE_INSENSITIVE_ORDER);


 


for (int i=0; i < arrayList.length; i++) {

// Prevent directory listing expanding if we will blow VARCHAR2 limit.


if ((list.length() + arrayList[i].length() + 1) > 32767)


break;


 


if (!list.equals(""))


list += "," + arrayList[i];


else

list += arrayList[i];

}


return list;

}


 


public static int mkdir (String path) {


File myFile = new File (path);


if (myFile.mkdir()) return SUCCESS; else return FAILURE;

}


 


public static int mkdirs (String path) {


File myFile = new File (path);


if (myFile.mkdirs()) return SUCCESS; else return FAILURE;

}


 


public static int renameTo (String fromPath, String toPath) {


File myFromFile = new File (fromPath);


File myToFile = new File (toPath);


if (myFromFile.renameTo(myToFile)) return SUCCESS; else return FAILURE;

}


 


public static int setReadOnly (String path) {


File myFile = new File (path);


if (myFile.setReadOnly()) return SUCCESS; else return FAILURE;

}


 


public static int copy (String fromPath, String toPath) {


try {


File myFromFile = new File (fromPath);


File myToFile = new File (toPath);


 


InputStream in = new FileInputStream(myFromFile);


OutputStream out = new FileOutputStream(myToFile);


 


byte[] buf = new byte[1024];


int len;


while ((len = in.read(buf)) > 0) {


out.write(buf, 0, len);

}


in.close();


out.close();


return SUCCESS;

}


catch (Exception ex) {


return FAILURE;

}

}

};

/


 

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

/* Usage of File Handler Class library */

PROCEDURE USP_GET_DIR_LIST( p_directory in VARCHAR2,p_category IN VARCHAR2)


as language java

name 'FileHandler.getList( java.lang.String, java.lang.String )';