/*
<Params>
CompanyName=ftString
Street=ftString
City=ftString
PostCode=ftString
Telephone=ftString
Email=ftString
SetmoreKey=ftString
</Params>
*/

/* Check to see if a company with the CompanyName and Email exists.*/
DECLARE ClientID INTEGER;
SET ClientID = COALESCE((SELECT top 1 CompanyCounter FROM Company WHERE
(CompanyName = :CompanyName) ),-1) ;


/* If the company does not exist then create it. */
IF ClientID = -1 THEN
INSERT INTO Company
(
  CompanyName,
  Address1,
  Town,
  PostCode,
  MainTelephone,
  EmailAddress
)
VALUES
(
:CompanyName,
:Street,
:City,
:PostCode,
:Telephone,
:Email
);

/* Get the previously created company's id */
SET ClientID = (SELECT LASTAUTOINC FROM #Dummy);
END IF;

/* Search for the setmore customer key in the SetmoreCustomers table */
DECLARE BandKey TEXT;
SET BandKey = COALESCE((SELECT top 1 CustomerKey FROM SetmoreCustomers WHERE
(CustomerKey = :SetmoreKey) ), '') ;

/* If the key was not found then add the CompanyID and SetmoreID to the
SetmoreCustomers table */
IF BandKey = '' THEN
INSERT INTO SetmoreCustomers
(
    CompanyID,
    CustomerKey
)
VALUES
(
    ClientID,
    :SetmoreKey
);

END IF;

/* Return the company */
SELECT CompanyCounter, CompanyName, Address1, Town, PostCode, MainTelephone,
EmailAddress FROM Company WHERE CompanyCounter = ClientID;