Reputation: 599
I have a Table called Couple
which has the following Fields CoupleId, HusbandId , WifeId ,
StartDate , EndDate
The previous Table contains informations about couple, The CoupleId
is a primary key
HusbandId
and WifeId
are Foreign keys form another Table Named Person
StartDate
and EndDate
represent the start/end date of marriage that happens between a male with HusbandId
and female with WifeId
in my problem i have a condition that w female can't married to two or more male at same time "Synchronous marriage"
and i have the following query
SELECT
DISTINCT A.WifeID
FROM
Couple A
INNER JOIN Couple B
ON A.WifeID = B.WifeID
AND A.HusbandID <> B.HusbandID
AND A.StartDate < B.EndDate
AND A.EndDate > B.StartDate;
which returns any female who has Synchronous marriage " Married to two or more male at same time"
I want to write trigger which fire when somebody want to insert or update the couple
table ,and i want this trigger allow the modification only if it make no fault information on it ( for example if someone insert a row on couple table and this row make the wife with #4 married to tow or more person at same time, this insertion must not complete because it make wrong info in the table)
can any one help me at this point ?
Upvotes: 1
Views: 709
Reputation: 79929
You can solve this without a trigger. Make a Composite primary key of these three keys in the Couples
table like so:
PRIMARY KEY(CoupleId, HusbandId, WifeId)
This will ensure the uniqueness of the HusbandId
and WifeId
for each coupleId
.
Here is a demo for the schema design for these two tables:
If you want to do this using a TRIGGER, try this:
CREATE TRIGGER WhenInsertOrUpdate
ON Couples
INSTEAD OF INSERT, UPDATE
AS
IF (NOT EXISTS( SELECT c.CoupleId
FROM Couples c
INNER JOIN Inserted i ON c.HusbandId = i.HusbandId
AND c.WifeId = i.WifeId
AND c.EndDate IS NULL))
BEGIN
INSERT INTO Couples
SELECT CoupleId, HusbandId, WifeId, StartDate, Enddate
FROM Inserted
END
ELSE BEGIN
--- You can put here an update..
END
GO;
Updated SQL Fiddle Demo using a trigger.
This is just an example, you have to provide an update statement in the ELSE
block if you need.
Upvotes: 2