I have to create a trigger or stored procedure for an address insert. This address insert can be on multiple tables. I don't know a lot about triggers and stored procedures so I can use some help.
See here for the database schema:
This in Dutch so here is some translation:
- Postcode = Postal code/zip code
- Huisnummer = Housenumber
- Plaatsnaam= City name
- Straat = Street
- Provincie = State
- Bedrijfsnaam = Company name
- Afdelingsnaam = Departement name
I must create a stored procedure/trigger that restricts making a insert/update into the tables ADDRESS
, STREETPART
and CITY
. These tables can only be inserted/updated when a insert/update is made in the following tables: COMPANY
, DEPARTMENT
, DEPARTMENTVISITINGADDRESS
, CUSTOMER
or EMPLOYEE
.
I also don't know how I can restrict this.
Because of the current foreign key structure (which I cannot change) there must be matching address in the ADRESS
, STREETPART
and CITY
tables before an insert can be made in following tables: COMPANY, DEPARTMENT, DEPARTMENTVISITINGADDRESS, CUSTOMER, EMPLOYEE
.
So the structure must be something like this: a user makes a insert into on the following tables: COMPANY, DEPARTMENT, DEPARTMENTVISITINGADDRESS, CUSTOMER, EMPLOYEE
. But before the insert is made into one of this tables a insert must be made first into the the tables CITY
(only if the city doesn't exists yet), STREETPART
and ADRESS
.
Firstly must be checked if the inserted postal code + housenumber is valid. I have a external postal code database where can be checked if the combination postcal code + housenumber is valid.The code below represents this:
DECLARE @POSTALCODE VARCHAR(6)
DECLARE @HOUSENUMBER INT
SELECT @POSTALCODE = POSTALCODE FROM INSERTED
SELECT @HOUSENUMBER = HOUSENUMBER FROM INSERTED
IF NOT EXISTS
(
SELECT PostalCode, MinNumber,MaxNumber
FROM PostalCode_DB.DBO.PostalCodes_NL
where @POSTALCODE = PostalCode and @HOUSENUMBER between MinNumber and MaxNumber
)
BEGIN
RAISERROR('Invalid combination postal code and house number', 16, 1)
ROLLBACK TRANSACTION
END
If the combination postal code + housenumber is valid there must be a check if the city is already in the CITY table. If yes, the state name and city matching the postal code must be inserted into the CITY table (the city name and state name are also in the external postal code database). After that a insert must be made into the STREETPART table (the street name mathing the postal code is also in the external postal code database). After that a insert must be made in the ADRESS table. The last step is to make a insert in the orginal insert table: COMPANY, DEPARTMENT, DEPARTMENTVISITINGADDRESS, CUSTOMER or EMPLOYEE.
Thank you for your help!