I need a little help with a query I am writing. I have broken it down to its most simple form.
An example of my table structure is shown below (I have altered it for clarity):
Users
UserId int -- PK Identity
Username varchar(30)
DirectReports
DirectReportId int -- PK Identity
UserId int -- FK to Users.UserId
ManagerId -- FK to Users.UserId
Documents
DocumentId int -- PK Identity
DocumentOwner int -- FK to Users.UserId
DocumentName varchar(30)
CreatedBy int -- FK to Users.UserId
CreatedDate datetime
What I need to do, is allow users who have created a document to be able to see their own document.
So I use:
CREATE PROCEDURE GetUsersDocuments
@UserId INT = null
AS
BEGIN
SET NOCOUNT ON;
Select * from Documents D
Where D.CreatedBy = ISNULL(@UserId, D.CreatedBy)
END
Which returns all documents created by a specific user.
However the business rules of the model, also dictate that another user may create a document on behalf of a user. So a user needs visibility of all records created by themselves, and all documents which they have ownership of:
CREATE PROCEDURE GetUsersDocuments
@UserId INT = null
AS
BEGIN
SET NOCOUNT ON;
Select * from Documents D
Where D.CreatedBy = ISNULL(@UserId, D.CreatedBy)
OR D.DocumentOwner = ISNULL(@UserId, D.DocumentOwner)
END
All works well. However, I have just been informed, that all direct reports of a user should have visibility of both documents created by a User, and documents a User has ownership of.
Given the example table structure I have defined, how would I express this in terms of a query?
Many Thanks
1 Answer