I'm creating a simple directory listing page where you can specify what kind of thing you want to list in the directory e.g. a person or a company.
Each user has an UserTypeID
and there is a dbo.UserType
lookup table. The dbo.UserType
lookup table is like this:
UserTypeID | UserTypeParentID | Name
1 NULL Person
2 NULL Company
3 2 IT
4 3 Accounting Software
In the dbo.Users
table we have records like this:
UserID | UserTypeID | Name
1 1 Jenny Smith
2 1 Malcolm Brown
3 2 Wall Mart
4 3 Microsoft
5 4 Sage
My SQL (so far) is very simple: (excuse the pseudo-code style)
DECLARE @UserTypeID int
SELECT
*
FROM
dbo.Users u
INNER JOIN
dbo.UserType ut
WHERE
ut.UserTypeID = @UserTypeID
The problem is here is that when people want to search for companies they will enter in '2' as the UserTypeID
. But both Microsoft and Sage won't show up because their UserTypeID
s are 3 and 4 respectively. But its the final UserTypeParentID
which tells me that they're both Companies.
How could I rewrite the SQL to ask it to return to return records where the UserTypeID = @UserTypeID
or where its final UserTypeParentID
is also equal to @UserTypeID
. Or am I going about this the wrong way?