As discussed above.
One option would be to have tables similar to this ...
create table person
(
PersonId int identity(1,1) primary key,
PersonName varchar(max),
userType char,
manager_id int FOREIGN KEY REFERENCES person(PersonId) NULL
)
create table AuthorisedUsers
(
AuthId int identity(1,1) primary key,
username varchar(max),
password varchar(max),
P_id int FOREIGN KEY REFERENCES person(PersonId) NOT NULL
)
Where
userType
will be 'C' for a customer and 'M' for a manager.
Note that password should not be stored in plain text - I recommend you read
Beginners guide to a secure way of storing passwords[
^] (or one of the other Code Project articles on the subject)
Then you can do things like
INSERT INTO person VALUES ('A Customer', 'C', null)
INSERT INTO person VALUES ('A Manager', 'M', null)
INSERT INTO person VALUES ('Customer 2', 'C', 2)
INSERT INTO person VALUES ('Customer 3', 'C', 2)
Then you can do
--Find all of the Customers who have 'A Manager' as their manager
SELECT * FROM person WHERE manager_id = (SELECT personid from person WHERE personname = 'A Manager')
and get
PersonId PersonName UserType Manager_id
3 Customer 2 C 2
4 Customer 3 C 2
You then went on to say that a Customer could be their own manager e.g.
INSERT INTO person VALUES('Customer 4','C', null)
UPDATE person SET manager_id = (SELECT PersonId FROM person WHERE PersonName = 'Customer 4')
WHERE PersonName = 'Customer 4'
This now raises an interesting problem. Consider "list all persons who are managers". Intuitively you would write
SELECT * FROM person WHERE userType = 'M'
But Customer 4 doesn't appear in that list because they are BOTH a customer AND a manager. You could write
SELECT * FROM person WHERE PersonId IN
(SELECT manager_id FROM person WHERE manager_id is not null)
Yuk! And it sort of makes userType redundant.
If a person can have many roles (more than 1) we need to revisit the database schema:
create table person
(
PersonId int identity(1,1) primary key,
PersonName varchar(max),
userType char,
manager_id int FOREIGN KEY REFERENCES person(PersonId) NULL
)
Introduce a new table which will be the "list" of roles for each person
create table UserRoles
(
roleId int identity(1,1) primary key,
ShortKey char,
P_id int FOREIGN KEY REFERENCES person(PersonId) NOT NULL
)
Insert some data for the persons we already have
insert into UserRoles values
('C', 1), -- A Customer
('M', 2), -- A Manager
('C', 3), -- Customer 2
('C', 4), -- Customer 3
('C', 5), -- Customer 4 as a Customer
('M', 5) -- Customer 4 as a Manager
Now you can find (all!) the managers like this
select * from person P
inner join UserRoles U on P.PersonId = U.P_id
where U.ShortKey = 'M'