/*
<Params>
FullName=ftstring
FirstName=ftstring
LastName=ftstring
Email=ftstring
Phone=ftstring
CompanyID=integer
</Params>
*/


/* Search for Person in Name2 */
DECLARE PersonID INTEGER;
SET PersonID = COALESCE((SELECT top 1 NameCounter FROM Name2 WHERE (FullName = :FullName) ),-1) ;

/* Create Person if not found */
IF PersonID = -1 THEN
    INSERT INTO Name2 (FORENAME, SURNAME, EMAIL, Telephone)
    VALUES (:FirstName, :LastName, :Email, :Phone);

    /* Set PersonID to the last created counter */
    SET PersonID = (SELECT LASTAUTOINC FROM #Dummy);

END IF;

/* Search for Person and Company in CONTACTS */
DECLARE ContactID INTEGER;
SET ContactID = COALESCE((SELECT top 1 ContactsCounter FROM CONTACTS WHERE (Company = :CompanyID AND Person = PersonID) ),-1) ;

/* Create a new Contact if not found */
IF ContactID = -1 THEN
    INSERT INTO CONTACTS (Company, Person, TelephoneNumber, Email)
    VALUES (CAST(:CompanyID AS INTEGER), PersonID, :Phone, :Email);

    /* Set ContactID to the last created counter */
    SET ContactID = (SELECT LASTAUTOINC FROM #Dummy);

END IF;

SELECT * FROM CONTACTS WHERE ContactsCounter = ContactID;