How to avoid circular relationship in SQL-Server?
Posted
by Shimmy
on Stack Overflow
See other posts from Stack Overflow
or by Shimmy
Published on 2009-12-22T08:26:39Z
Indexed on
2010/04/29
11:07 UTC
Read the original article
Hit count: 713
I am creating a self-related table:
Table Item
columns:
ItemId int - PK;
Amount money - not null;
Price money - a computed column using a UDF that retrieves value according to the items ancestors' Amount.
ParentItemId int - nullable, reference to another ItemId in this table.
I need to avoid a loop, meaning, a sibling cannot become an ancestor of his ancestors, meaning, if ItemId=2 ParentItemId = 1, then ItemId 1 ParentItemId = 2 shouldn't be allowed.
I don't know what should be the best practice in this situation. I think I should add a CK that gets a Scalar value from a UDF or whatever else.
EDIT: Another option is to create an INSTEAD OF trigger and put in 1 transaction the update of the ParentItemId field and selecting the Price field from the @@RowIdentity, if it fails cancel transaction, but I would prefer a UDF validating.
Any ideas are sincerely welcomed.
© Stack Overflow or respective owner