Help on a somewhat complex Trigger!

Hi, I'm new to triggers and I want to be able to enforce a somewhat complex rule on a table.  Here is the definition for table 'xyz':

id_node int not null primary key,
parentid int not null,
nodetype smallint not null,
nodetext varchar(20) not null

The rules I want to enforce are the following:

(1) For each insert on this table, the first record inserted MUST have nodetype = 0.  Any subsequent rows inserted must have a nodetype > 0.  This will enforce the rule that there should exist only one row in the table with nodetype = 0.
(2) If rule 1 has been satisfied, then an insert on this table should fail if and only if the parentid column does not reference an id_node already in the table.

The effect, if you haven't noticed already, is to represent a tree-structure in the table.  So essentially, you start with inserting the root node (nodetype = 0), and then traverse the tree structure in order....inserting each node along the way.

I have a (non-tested) start to a trigger definition here:

create trigger trig_xyz
  after insert on xyz
  referencing new row as nrow
  for each row mode db2sql
  -- enforce rule 1
  when (count(*) = 0) then
    when nrow.nodetype<>0 then -- raise exception (first node inserted must be the root node)
  else
    -- enforce rule 2
    case when nrow.nodetype=0 then -- raise exception (only one root node allowed!)
    else
      when not exists(select id_node from xyz) then -- raise exception (parentid must reference a node in this table)


....SOMETHING like that.  Any help would be greatly appreciated!

Thanks.
- TIM
simulantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

simulantAuthor Commented:
I found a solution to enforce rule #1:

-- trigger to enforce the rule that only one root node may exist in the table
create trigger trg_xyz
  no cascade before
  insert on xyz
  referencing new as nrow
  for each row mode db2sql
  when (
    nrow.nodetype = 0 and
    exists (select * from xyz where nodetype = 0)
  )
    signal sqlstate '88W01' ('Only one root node (nodetype=0) may exist')
  ;


Still working on rule #2!
0
BigSchmuhCommented:
I have an idea without using any triggers using a classic Foreign Key constraint.

Did you try defining a FK on the self table PK ?
That way, the first record can be inserted relative to itself and every others will follow your #2 rules...

Example:
Create Table MyTree(
   MyPk INTEGER NOT NULL PRIMARY KEY DEFAULT 0
  ,MyFk INTEGER NOT NULL REFERENCES MyTree(MyPk) DEFAULT 0
  ,Cel1 Varchar(10), Cel2 Varchar(20) )

==> Think although that you need rule #3 to avoid circular references even if you use the DB2 specific syntax for recursive SELECT (Starting with a WITH keyword instead of a SELECT one...)


Hope this helps.
0
simulantAuthor Commented:
Ok, I came up with some solutions.  These triggers work great!

-- table must contain a root node before inserting rows
create trigger i_enodes_root1
  no cascade before
  insert on archive.enodes_tmp
  referencing new as nrow
  for each row mode db2sql
  when (
    not exists (select * from enodes_tmp where nodetype = 0) and
    nrow.nodetype > 0
  )
  signal sqlstate '88001' ('table must contain a single root node (nodetype=0)');


-- only one root node should exist in this table
create trigger i_enodes_root2
  no cascade before
  insert on archive.enodes_tmp
  referencing new as nrow
  for each row mode db2sql
  when (
    nrow.nodetype = 0 and
    exists (select * from enodes_tmp where nodetype = 0)
  )
  signal sqlstate '88002' ('table must contain only one root node (nodetype=0)');


-- each parentid must reference an id_node already inserted
create trigger i_enodes_parent
  no cascade before
  insert on archive.enodes_tmp
  referencing new as nrow
  for each row mode db2sql
  when (
    exists (select * from enodes_tmp where nodetype = 0) and
    not exists (select * from enodes_tmp where id_node = nrow.parentid)
  )
  signal sqlstate '88003' ('parentid must reference an id_node already inserted');


-- each parentid must reference an id_node already inserted
create trigger u_enodes_parent
  no cascade before
  update of parentid on archive.enodes_tmp
  referencing new as nrow
  for each row mode db2sql
  when (
    exists (select * from enodes_tmp where nodetype = 0) and
    not exists (select * from enodes_tmp where id_node = nrow.parentid)
  )
  signal sqlstate '88003' ('parentid must reference an id_node already inserted');


-- a node cannot be deleted if it has children
create trigger d_enodes_child
  no cascade before
  delete on archive.enodes_tmp
  referencing old as orow
  for each row mode db2sql
  when (
    exists (select * from enodes_tmp where parentid = orow.id_node)
  )
  signal sqlstate '88004' ('cannot delete a node that has children');

0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

BigSchmuhCommented:
Those are certainly nice triggers but:
-Why do you maintains many BEFORE INSERT triggers instead of only one
-Did you try using a simple Foreign Key (as posted above)

Hope this helps.
0
simulantAuthor Commented:
Yes, I would like to combine those insert triggers into one.  I suppose I could use a case statement to handle the various conditions....I will try this out.  As for enforcing rule #2 as a foreign key column, it is a great idea, but it is not as strict as I want it to be.  For example, it allows the following:

insert into xyz (id_node, parentid) values (1,1);
insert into xyz (id_node, parentid) values (2,2);

I want the insertions to this tree table to basically start at the root, and traverse down the tree, inserting each node along the way.  So the above would violate this because the second insert is not creating a child of the root.  The trigger, however, does enforce this.

Thanks for your help!
0
simulantAuthor Commented:
How would you go about combining the 3 insert triggers defined above into a single trigger?  I'm having a tough time so far with this...

Thanks in advance
0
BigSchmuhCommented:
1/ Add a column constraint to fully implement rule #1
A simple column constraint can be defined to avoid having values other than (0,0) based on the following expressions:
   (MyPk=0 AND MyFk=0) OR ((MyPk>0) AND (MyPk<>MyFk))

2/ Combining your 3 insert triggers
That confirm maintaining triggers is a hard time...
==> I can not look at this right now but will later on if you ask me to

Hope this helps.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
DB2

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.