I have an employee table with manager field and a foreign key (between manager and employee id) relation to itself. Now I want to prevent any circular relations, e.g suppose employee id 2 has manager (employee id 1). How can I now prevent someone to enter employee 2 as manager for employee 1. I know I can do it programatically. Is there a way I can do it in design. Can I use this in T-SQL:
where c.asset_id = v.parent_asset_id and (c.asset_type,d.asset_type,v.assoc_type) in (select m.asset_key,n.asset_key,o.association_key from dbo.t_association_rule o, dbo.t_asset_master m, dbo.t_asset_master n)
I believe the introduction of Assertions in the SQL standard allows for this type of "constraint" to be declared (as opposed to programmed). However, I don't believe any of the larger database vendors have implemented assertions yet. Frankly, I believe there are still some significant technological hurdles to be overcome before assertions can be implemented without resulting in horrific performance issues. This model of trees is popular, though clunky in today's relational databases. Oracle and DB2 have extensions to SQL that allow for the traversal of trees; I don't believe SQL Server does. Unfortunately, I believe that your only solutions are to implement your constraint programmatically through triggers (sorry) or alter your data design (sorry). With regard to altering your data design, I might recommend Joe Celko's Associative Model of Trees covered in his book, SQL for Smarties: Advanced SQL Programming.
For More Information
- Dozens more answers to tough SQL questions from Jason Law are available here.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.