This is a contrived example, but consider a scenario where employees have working locations, and where employees have managers who also have working locations:
create table WorkingLocation (
ID int not null primary key identity(1,1),
Name varchar(50)
)
create table Employee (
ID int not null primary key identity(1,1),
Name varchar(50),
WorkingLocationID int null,
ManagerID int null,
constraint FK_Employee_WorkingLocation foreign key (WorkingLocationID) references WorkingLocation (ID),
constraint FK_Employee_Manager foreign key (ManagerID) references Employee (ID)
)
Now consider a business rule that wants the employee's WorkingLocation
, but will settle for his manager's WorkingLocation
if he doesn't have one. At this point you have two options:
1: Have a query that gets both and let business rules decide which to use:
select
e.*,
emp_location.*,
mgr_location.*
from Employee e
left join WorkingLocation emp_location on e.WorkingLocationID = emp_location.ID
left join Employee mgr on e.ManagerID = mgr.ID
left join WorkingLocation mgr_location on mgr.WorkingLocationID = mgr_location.ID
where e.ID = @id
2: Make separate calls to the database to retrieve the manager's details if the employee has no WorkingLocation
set.
Which do you prefer and why?