Solved

Help on a somewhat complex Trigger!

Posted on 2003-12-08
7
601 Views
Last Modified: 2012-06-27
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
0
Comment
Question by:simulant
  • 4
  • 3
7 Comments
 

Author Comment

by:simulant
ID: 9904952
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
 
LVL 18

Expert Comment

by:BigSchmuh
ID: 9906770
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
 

Author Comment

by:simulant
ID: 9906959
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 18

Expert Comment

by:BigSchmuh
ID: 9910312
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
 

Author Comment

by:simulant
ID: 9912966
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
 

Author Comment

by:simulant
ID: 9915568
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
 
LVL 18

Accepted Solution

by:
BigSchmuh earned 125 total points
ID: 9919305
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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

November 2009 Recently, a question came up in the DB2 forum regarding the date format in DB2 UDB for AS/400.  Apparently in UDB LUW (Linux/Unix/Windows), the date format is a system-wide setting, and is not controlled at the session level.  I'm n…
Recursive SQL in UDB/LUW (it really isn't that hard to do) Recursive SQL is most often used to convert columns to rows or rows to columns.  A previous article described the process of converting rows to columns.  This article will build off of th…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now