Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding Unique Contstraint

Status
Not open for further replies.

nlaliberte

Programmer
Apr 26, 2007
79
US
Good Afternoon,

I have a simple relationship table that I need to add a contrainst to. The table is supposed to be a parent/child relationship, as well as the date the relationship is effective. See Below:

CREATE TABLE relation
(
child_id INT
,parent_id INT
,acq_date DATETIME
)


We have found in the table the following two records;

Child_id Parent_id Acq_date
12 6 10/31/2008
6 12 10/31/2008


Obviously the son of a father can't be the father's father. (I know it sounds confusing but I'm sure you all understand).

So I need to put a contraint on that does not allow a record to be entered if there is already a relation where the child is the father.



If it helps, here is how I would apply the constraint to an insert statement, maybe this will clarify the logic I'm looking for.

INSERT INTO relation
(
child_id
,parent_id
,acq_date
)
SELECT
i.child_id
,i.parent_id
,i.acq_date
FROM input i
WHERE NOT EXISTS (
SELECT r.*
FROM relation r
WHERE r.child_id = i.parent_id
AND r.parent_id = i.child_id
)


Can anyone help me with this piece of code? It would be greatly appreciated.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top