sql - Restrict database tree depth -



sql - Restrict database tree depth -

typically when represent parent kid hierarchy have table follows (i might add together additional depth columns speed things up), parents , children both foreign key relationships rows same entity table.

entity relationships composite pkey kid id parent id

what trying figure out how limit depth of tree one. in other words, if parent of child, how prevent parent beingness kid in itself, impossible have grandparents or further?

depending on rdbms, can handle in insert/update trigger. restricting parent not kid shouldn't bad (although hate using triggers more necessary). if trying limit number of levels (say 100) might start run performance issues.

in ms sql server can utilize user-defined functions in constraints. there limits however, don't know if work here. i'll seek test though.

edit:

i tested on ms sql server 2008 , looks works correctly:

create function dbo.is_child (@parent_id int) returns bit begin declare @return bit if exists (select * dbo.test_trees child_id = @parent_id) set @return = 1 else set @return = 0 homecoming @return end go create table dbo.test_tree_objects ( my_id int not null, constraint pk_test_tree_objects primary key clustered (my_id) ) create table dbo.test_trees ( my_id int not null identity, parent_id int not null check (dbo.is_child(parent_id) = 0), child_id int not null, constraint pk_test_trees primary key clustered (my_id), constraint fk_test_trees_parent_id foreign key (parent_id) references dbo.test_tree_objects (my_id), constraint fk_test_trees_child_id foreign key (child_id) references dbo.test_tree_objects (my_id) ) go insert dbo.test_tree_objects (my_id) values (1), (2), (3), (4), (5) go insert dbo.test_trees (parent_id, child_id) values (1, 2) insert dbo.test_trees (parent_id, child_id) values (2, 3) drop table dbo.test_trees drop table dbo.test_tree_objects drop function dbo.is_child go

sql database tree relationship

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -