/*
<Params>
pCompanyName=ftString
pStreet=ftString
pCity=ftString
pPostCode=ftString
pTelephone=ftString
pEmail=ftString
</Params>
*/

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


/* If the company does not exist then create it. */
IF CompanyID = -1 THEN
INSERT INTO Company
(
  CompanyName,
  Address1,
  Town,
  PostCode,
  MainTelephone,
  EmailAddress
)
VALUES
(
:pCompanyName,
:pStreet,
:pCity,
:pPostCode,
:pTelephone,
:pEmail
);

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

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