[quoted text, click to view] >> I have a user assigned multiple roles and a role can be inherited
from multiple parents (see below). How do I answer such questions as
"How many roles does the user belong to?" (no re-enter allowed and no
deep level restriction) <<
Please read ISO-11179 so your data element names will make sense. The
prefix that tells us a table is a table is redundant and useless.
Also, in what world are all strings NVARCHAR(99)? How much research did
you do at the Post Office, ISO, systems manuals, etc. for your data
elements? How many weeks did you spend looking for any standards or for
reasonable limits and datatypes to preserve your data integrity? What
system has passwords longer than CHAR(12)? Etc.
CREATE TABLE Users
(user_id INTEGER NOT NULL PRIMARY KEY,
name NVARCHAR(35) NOT NULL, -- foreign names allowed
password CHAR(12) NOT NULL);
CREATE TABLE Roles
(role_id INTEGER NOT NULL PRIMARY KEY,
role_name NVARCHAR(35) NOT NULL);
CREATE TABLE UsersRoles
(user_id INTEGER NOT NULL
REFERENCES Users (user_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
role_id INTEGER NOT NULL
REFERENCES Roles (role_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
PRIMARY KEY (user_id, role_id));
Now this is cleaned up, what are your rules? Trees do not allow
multiple parents and a path enumeration or nested sets model would give
us the entire path in one query. So, what about cycles? Is this a
lattice or a general graph?
What you might wind up with is a table that covers all the levels from a
given role thru all its ancestors. Ugly, but very quick and fairly easy
to maintain once built.
CREATE TABLE Role_Inheritance
(role_id INTEGER NOT NULL
REFERENCES Roles (role_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
ancestor_role_id INTEGER NOT NULL
REFERENCES Roles (role_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
level INTEGER NOT NULL CHECK (level >= 0),
<< horrible check constraints for cycles and other rules >>,
PRIMARY KEY (role_id, ancestor_role_id));
--CELKO--
===========================
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are.
*** Sent via Developersdex
http://www.developersdex.com ***