I’m writing a stored procedure that gets data for a whole screen. How can I re-use the result of one select to feed into a second select? This for performance reasons
Simplified Example:
I have 4 tables
- Responsible
- Action (has foreign key to Responsible)
- Group (has foreign key to Responsible)
- Case (has foreign key to group)
The stored procedure gets a caseid to retrieve the data
First select gets the details of the case, group and its related responsible record:
select
Case.Date,
Case.Name,
Group.Name,
Responsible.Name
Responsible.ResponsibleID
from Case
inner join Group on Group.GroupID=Case.GroupID
inner join Responsible on Responsible.ResponsibleID=Group.ResponsibleID
where CaseID=@CaseID
Second select must get all actions that the responsible is assigned to. We only have the caseID and therefor we must reconstruct the joins again:
select Action.*
from Case
inner join Group on Group.GroupID=Case.GroupID
inner join Responsible on Responsible.ResponsibleID=Group.ResponsibleID
inner join Action on Action.ResponsibleID=Responsible.ResponsibleID
where CaseID=@CaseID
If it would be possible to reuse the variable from the previous result it would be possible to create the following query which would probably be better for performance:
Select * from Action where ResponsibleID={ResultSet1}.ResponsibleID
Consider holding your results in a table variable. This will allow you to perform multiple SQL operations on that result set from your permanent tables.