Slow Left Outer Join - sql-server

I wonder if anyone can advise me on this issue. I have a query which runs slowly when a left outer join is introduced. Without the left outer join (Inner instead) it runs pretty much immediately, but with the left outer it runs 20 seconds or more. The joined columns are indexed. My execution plan shows a hash match if that helps. Thank you again for your assistance..
Derek
SELECT DISTINCT
dbo.Staff.strStaffName AS [Staff Name], dbo.Staff.strEmailAddress1 AS NegEmailAddress, ISNULL(dbo.qryContactEmailDJ.Address,
dbo.Staff.strEmailAddress1) AS AppEmailAddress
FROM dbo.Contacts INNER JOIN
dbo.Staff ON dbo.Contacts.strResponsibilityOf = dbo.Staff.strStaffName LEFT OUTER JOIN
dbo.qryContactEmailDJ ON dbo.Contacts.ContactPK = dbo.qryContactEmailDJ.ContactFK INNER JOIN
dbo.Property ON dbo.Contacts.CompanyFK = dbo.Property.CompanyFK INNER JOIN
dbo.qryLS_ApplicantLastMadeActive ON dbo.Contacts.ContactPK = dbo.qryLS_ApplicantLastMadeActive.ContactPK
WHERE (dbo.Contacts.strApplicantStatus = 'Active')
AND (CONVERT(VarChar, dbo.qryLS_ApplicantLastMadeActive.LatestActiveDate, 112) = CONVERT(VarChar, GETDATE() - 84,112))

This will make it a bit more readable and faster, the issue is your way of comparing the dates in the WHERE clause:
SELECT --(do you really need distinct ?)
Staff.strStaffName AS [Staff Name],
Staff.strEmailAddress1 AS NegEmailAddress,
ISNULL(con.qryContactEmailDJ.Address, Staff.strEmailAddress1) AS AppEmailAddress
FROM dbo.Contacts
JOIN dbo.Staff
ON Contacts.strResponsibilityOf = Staff.strStaffName
LEFT JOIN dbo.qryContactEmailDJ con
ON Contacts.ContactPK = con.ContactFK
JOIN dbo.Property
ON Contacts.CompanyFK = Property.CompanyFK
JOIN dbo.qryLS_ApplicantLastMadeActive qryl
ON Contacts.ContactPK = qryl.ContactPK
WHERE
(Contacts.strApplicantStatus = 'Active')
AND qryl.LatestActiveDate >= dateadd(d, datediff(d, 0, GETDATE()), -84)
AND qryl.LatestActiveDate < dateadd(d, datediff(d, 0, GETDATE()), -83)

Related

Joining query sql server

I'm after some help please i'm new to SQL, can you help me join these to queries below I want all the data from the first query to be displayed and only the information that matches to be showed on the second query.
Part and subkey1 is the join
Thank you.
SELECT RHeads.[Document],
RLines.Part,
RHeads.Supp,
RHeads.DATETIME,
RLines.Unit,
RLines.CQty,
RHeads.POrder,
RHeads.Corder,
RHeads.Branch
FROM RLines
RIGHT OUTER JOIN RHeads ON RLines.[Document] = RHeads.[Document]
WHERE (RHeads.DATETIME >= DATEADD(MONTH, - 3, GETDATE()))
AND (RHeads.Corder = '02022076')
ORDER BY RHeads.DATETIME DESC;
SELECT Mvpr.Prefix,
Mvpr.SubKey1,
Mvpr.SubKey2,
Mvpr.A12
FROM Mvpr
INNER JOIN vwProduct ON Mvpr.SubKey1 = vwProduct.KeyCode
WHERE (Mvpr.Prefix = 'c');
Just stick both of these SQL statements into their own subquery (using parantheses) and give each subquery an alias so we can refer to it's result set in the main query:
SELECT
t1.*,
t2.*
FROM
(
SELECT RHeads.[Document],
RLines.Part,
RHeads.Supp,
RHeads.DATETIME,
RLines.Unit,
RLines.CQty,
RHeads.POrder,
RHeads.Corder,
RHeads.Branch
FROM RLines
RIGHT OUTER JOIN RHeads ON RLines.[Document] = RHeads.[Document]
WHERE (RHeads.DATETIME >= DATEADD(MONTH, - 3, GETDATE()))
AND (RHeads.Corder = '02022076')
) t1
LEFT OUTER JOIN
(
SELECT Mvpr.Prefix,
Mvpr.SubKey1,
Mvpr.SubKey2,
Mvpr.A12
FROM Mvpr
INNER JOIN vwProduct ON Mvpr.SubKey1 = vwProduct.KeyCode
WHERE (Mvpr.Prefix = 'c')
) t2 ON t1.Part = t2.SubKey1
ORDER BY t1.DATETIME DESC;
We're using a LEFT OUTER JOIN to get all of the records from t1 (first query) and only those records that match from t2 (second query).
Also I have moved the ORDER BY clause to the main query as you can't ORDER inside of a subquery (and even if you were allowed to, the ordering would be lost after the join so it would be superfluous).
Since you aren't doing any aggregating here, you could probably rewrite this without the subquery too.
I've made some assumptions about your data, but perhaps something like:
SELECT RHeads.[Document],
RLines.Part,
RHeads.Supp,
RHeads.DATETIME,
RLines.Unit,
RLines.CQty,
RHeads.POrder,
RHeads.Corder,
RHeads.Branch,
Mvpr.Prefix,
Mvpr.SubKey1,
Mvpr.SubKey2,
Mvpr.A12
FROM RHeads
LEFT OUTER JOIN RLines
ON RLines.[Document] = RHeads.[Document]
LEFT OUTER JOIN vwProduct
ON Mvpr.SubKey1 = vwProduct.KeyCode
LEFT OUTER JOIN Mvpr
ON vwProduct.KeyCode = Mvpr.Subkey1
AND Mvpr.Prefix = 'c'
WHERE
RHeads.DATETIME >= DATEADD(MONTH, - 3, GETDATE())
AND RHeads.Corder = '02022076'
If you want to maintain the granularity of the 1st query put them in CTEs and check existence:
;WITH Q1 AS(
SELECT RHeads.[Document],
RLines.Part,
RHeads.Supp,
RHeads.DATETIME,
RLines.Unit,
RLines.CQty,
RHeads.POrder,
RHeads.Corder,
RHeads.Branch
FROM RLines
RIGHT OUTER JOIN RHeads ON RLines.[Document] = RHeads.[Document]
WHERE (RHeads.DATETIME >= DATEADD(MONTH, - 3, GETDATE()))
AND (RHeads.Corder = '02022076')
), Q2 AS (
SELECT Mvpr.Prefix,
Mvpr.SubKey1,
Mvpr.SubKey2,
Mvpr.A12
FROM Mvpr
INNER JOIN vwProduct ON Mvpr.SubKey1 = vwProduct.KeyCode
WHERE (Mvpr.Prefix = 'c')
)
SELECT q1.*
FROM Q1 q1
WHERE EXISTS(
SELECT *
FROM Q2 q2
WHERE q1.Part = q2.SubKey1
)
ORDER BY q1.DATETIME DESC

What alternative do I have to a Left Join in this query?

I have this query that is used in a SSRS report that someone else created. The left join is the cause of the problem. If I change it to an inner join I get results (not the correct results) in about 15 seconds. With the Left Join I end up canceling the query after 20 minutes. I added an index to both Budgets.Professionals and Transactions.Professionals with no change in performance. Is there a way to rewrite the query and not use the Left Join?
SELECT
profs.ProfName as orig
,profs.Initials
,DATEPART(year, TransDate) as [Year]
,SUM(CASE WHEN IsFlatFee = 'Y' OR COALESCE(MT.Admin, 'N') = 'Y'
THEN 0.0
ELSE Units * (aph.assignedpercent/100) * isnull(B.rate, 0.0)
END) AS ctp
,SUM(CASE WHEN IsFlatFee = 'Y' OR COALESCE(MT.Admin, 'N') = 'Y'
THEN 0
ELSE Units
END * (aph.assignedpercent/100)) AS worked_hours
,SUM(Value * (aph.assignedpercent/100)) AS worked_value
, 0 AS billed_hours
,0 AS billed_value
,0 AS billed_netamt
, 0.0 as paid
, 0.0 as wo
FROM Transactions Trans
INNER JOIN Matters Matts ON Trans.matters = Matts.matters
INNER JOIN MatterTypes MT ON Matts.mattertype = MT.mattertypesdesc
and MT.Admin <> 'Y'
INNER JOIN Components Comps ON Comps.components = Trans.components
and Comps.CompType = 'F'
INNER JOIN AssignedProfsHistory APH on APH.Matters = Trans.Matters
and APH.AssignedType = 'Originating'
and Trans.TransDate between APH.EffectiveDate and
ISNULL(EndDate,'12/31/2099')
INNER JOIN Professionals profs on profs.Professionals = APH.Professionals
and profs.ProfType = 'Member'
and profs.IsActive = 'Y'
and profs.IsBillable = 'Y'
**LEFT join** (SELECT Budgets.Professionals as timekeeper, Budgets.Amount as
rate, Budgets.PeriodDate
FROM Matters Matts
INNER JOIN Budgets ON Matts.matters = Budgets.matters
and cast(Budgets.PeriodDate as Date) <= '2017-12-31'
AND MONTH('2017-12-31') = MONTH(Budgets.PeriodDate)
WHERE Matts.MatterID = '99999-99.003') as B
*on B.timekeeper = Trans.Professionals*
and YEAR(B.PeriodDate) = DATEPART(year, TransDate)
WHERE cast(transdate as DATE) between dateadd(day, 1, DATEADD(year, -3,
'2017-12-31')) and '2017-12-31'
GROUP BY profs.ProfName, profs.Initials, DATEPART(year, TransDate)
As Sean and Aaron said. There are too many things that are potentially an issue.
You seem (I'm guessing from column names) that you are joining on text columns mattertypesdesc for one. In fact most of the work is done against text columns. Even Matts.MatterID is textual. This may not be possible in your scenario but it would perform better if the tables had integer primary keys and you join on those.
Anyway, guessing aside.... You might get a quick win if you replace your sub query in the left join with a temp table.
so before you existing query just do ...
SELECT Budgets.Professionals as timekeeper, Budgets.Amount as rate, Budgets.PeriodDate
INTO #t
FROM Matters Matts
INNER JOIN Budgets ON Matts.matters = Budgets.matters
and cast(Budgets.PeriodDate as Date) <= '2017-12-31'
AND MONTH('2017-12-31') = MONTH(Budgets.PeriodDate)
WHERE Matts.MatterID = '99999-99.003'
then in your exisintg query, replace the subquery with
SELECT ...
...
...
LEFT JOIN #t as B
ON B.timekeeper = Trans.Professionals
....
You can also try with the APPLY operator... remove left join & it's on condition, use outer apply and include on conditions inside the outer apply script like
AND budgets.timekeeper = trans.professionals
AND year(budgets.perioddate) = datepart(year, transdate)
Sample
OUTER APPLY
(
SELECT budgets.professionals AS timekeeper,
budgets.amount AS rate,
budgets.perioddate
FROM matters matts
INNER JOIN budgets
ON matts.matters = budgets.matters
AND cast(budgets.perioddate AS date) <= '2017-12-31'
AND month('2017-12-31') = month(budgets.perioddate)
AND budgets.timekeeper = trans.professionals
AND year(budgets.perioddate) = datepart(year, transdate)
WHERE matts.matterid = '99999-99.003'
) AS b
Thanks everyone who responded. I took your suggestions and I was able to come up with a solution. The query that I had to kill after running for 2 hrs now finishes in about 14 seconds.
I ended up creating a cte at the beginning of the script.
;with cte as
(SELECT Transactions FROM Transactions t
WHERE cast(t.TransDate as DATE) between dateadd(day, 1, DATEADD(year, -3,
#EndDate)) and #EndDate)
Then I linked the CTE to Transactions.
FROM Transactions Trans
INNER JOIN cte ON cte.Transactions = Trans.Transactions
I then was able to remove the 'where' clause that was causing the issue.
WHERE cast(transdate as DATE) between dateadd(day, 1, DATEADD(year, -3,
#EndDate)) and #EndDate

How to break sales query results by day

I have a sales query by date range, where the date range is defined by user input. I would like to divide the results by day. i.e.: say the user input the date range from 01/01/16 - 01/15/16, I would like the break the results for each day.
I'm using DATENAME(DD,T1.[DocDate]) to break it, and it is kind of working, but the results are no accurate. I figure I have to use the same break in the Returns subquery. Please see the full query below:
Thank you
SELECT
'2016' as 'Year',
t4.remarks as 'Department',
DATENAME(DD,T1.[DocDate]) as 'Day',
sum(t0.[quantity])-(ISNULL(p.quantity,0)) as 'Quantity',
sum(t0.linetotal - t0.linetotal*t1.discprcnt/100)-(ISNULL(p.total,0)) as 'Total',
sum(T0.[GrssProfit])-(ISNULL(p.profit,0)) as 'Profit $',
(sum(T0.[GrssProfit])-(ISNULL(p.profit,0)))/(sum(t0.linetotal - t0.linetotal*t1.discprcnt/100)-(ISNULL(p.total,0)))*100 as 'Profit%'
FROM INV1 T0 with (nolock)
INNER JOIN OINV T1 with (nolock) on t0.docentry = t1.docnum
INNER JOIN OSLP T2 with (nolock) on t0.SlpCode = t2.SlpCode
LEFT JOIN OHEM T3 with (nolock) on t0.slpcode = t3.SalesPrson
LEFT JOIN OUDP T4 with (nolock) on t3.dept = t4.Code
--BEGINS QUERY FOR THE RETURNS--
left join (select t9.name as 'dept',sum(t5.quantity) as 'quantity',sum(t5.linetotal - t5.linetotal*t6.discprcnt/100) as 'total',sum(t5.grssprofit) as 'profit'
from [dbo].[rin1] t5 with (nolock)
inner join orin t6 with (nolock) on t5.docentry = t6.docentry
INNER JOIN OSLP T7 with (nolock) on t5.SlpCode = t7.SlpCode
LEFT JOIN OHEM T8 with (nolock) on t5.slpcode = t8.SalesPrson
LEFT JOIN OUDP T9 with (nolock) on t8.dept = t9.Code
INNER JOIN OITM T10 with (nolock) on t5.itemcode = t10.itemcode
where t5.docdate between '[%1]' and '[%2]' and t10.invntitem = 'Y'
and (t5.linetotal - (t5.linetotal*t6.discprcnt/100)) <> '0'
group by t9.name) p on p.dept = t4.name
--ENDS QUERY FOR THE RETURNS--
WHERE t1.docdate between '[%1]' and '[%2]'
and t4.remarks is not null
and t4.remarks = 'perfume provider'
and (t0.linetotal - (t0.linetotal*t1.discprcnt/100)) <> '0'
group by DATENAME(DD,T1.[DocDate]),t4.remarks,p.quantity,p.total,p.profit
Instead of a sub-query for your returns (with the same kind of group by as your Invoices query), you should use a UNION instead. Your Group-By is fine, but like you mentioned, your subquery is going to result in bad data.
Any time you have distinct "starting points" for your data, a Union is the way to go.

Duplicate records with Multiple joins

I had written a join query statement. that statement returns me multiple(duplicate) row again even though I'm having only single record on that.
declare #BenefitClass int ;
set #BenefitClass = (select BenefitClass From HJOB where userid='d76c5000-69e0-461e-92e1-3cfe7590d098' and CompanyId =1629)
select #BenefitClass;
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098' and bhsac.PlanInfoId=38044
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId and oems.EndDt > GETDATE()
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
For that I'm getting the result as second row as duplicate :
observe the result
Try this once it may help you
declare #BenefitClass int ;
set #BenefitClass = (select BenefitClass From HJOB where userid='d76c5000-69e0-461e-92e1-3cfe7590d098' and CompanyId =1629)
select #BenefitClass;
;with cte as (
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098' and bhsac.PlanInfoId=38044
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId and oems.EndDt > GETDATE()
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
)
select distinct EmployerContribution,
CatchUpValue ,Tier,planYear,Ischecked,EmployeeContribute,Id ,Value ,HSALmitId from cte
Please change your where condition as below:
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098'
and bhsac.PlanInfoId=38044
and oems.EndDt > GETDATE()

merging two stored procedures

So this is what i thought of doing but now the error i am getting is : Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause and not sure which part it means - the overall code i am trying to get open cases based on two different levels one is to return cases based on date range passed in and the other is to return cases based on just the begin date and before it.
Help will be great! :)
CODE:
SELECT
C.CaseNumber,
O.OfficeName,
CT.Description AS CaseType,
DATEADD(dd, 0, DATEDIFF(dd, 0, C.DateOpened)) AS DateOpened,
CR.Description AS Court,
CaseOfficeAppointment.OpenCases,
CaseOfficeAppointment.CloseCases
FROM
(
SELECT C.CaseId, O.OfficeId, CRT.CourtId,
(
SELECT COUNT(DISTINCT CD.CaseId)
FROM [Case] CD
INNER JOIN CaseOffice COD ON CD.CaseId = COD.CaseId
--INNER JOIN Court CR ON CD.CourtId = CR.CourtId
INNER JOIN Office OD ON COD.OfficeId = OD.OfficeId
LEFT OUTER JOIN CaseStatusChange CSC ON CD.CaseId = CSC.CaseId
--WHERE CR.CourtId = CRT.CourtId
WHERE OD.OfficeId = O.OfficeId
AND
( CD.DateOpened BETWEEN #BeginDate AND #EndDate
OR
CSC.DateReopened BETWEEN #BeginDate AND #EndDate
)
)AS OpenCases,
(
SELECT COUNT(DISTINCT CD.CaseId)
FROM [Case] CD
INNER JOIN CaseOffice COD ON CD.CaseId = COD.CaseId
--INNER JOIN Court CR ON CD.CourtId = CR.CourtId
INNER JOIN Office OD ON COD.OfficeId = OD.OfficeId
LEFT OUTER JOIN CaseStatusChange CSC ON CD.CaseId = CSC.CaseId
--WHERE CR.CourtId = CRT.CourtId
WHERE OD.OfficeId = O.OfficeId
AND
( CSC.DateClosed BETWEEN #BeginDate AND #EndDate
)
)AS CloseCases
FROM [Case] C
INNER JOIN [Appointment] A ON C.CaseId = A.CaseId
INNER JOIN [Office] O ON A.OfficeId = O.OfficeId
INNER JOIN [Court] CRT ON C.CourtId = CRT.CourtId
WHERE
-- Case was open (or reopened) during the date range
C.DateOpened BETWEEN #beginDate AND #endDate
OR
C.CaseId IN (SELECT CaseId FROM CaseStatusChange WHERE DateReopened BETWEEN #beginDate AND #endDate)
AND
-- Office had an appointment sometime during the date range
A.DateOn < #endDate AND (A.DateOff IS NULL OR A.DateOff BETWEEN #beginDate AND #endDate)
GROUP BY C.CaseId, O.OfficeId, CRT.CourtId,
(
SELECT OfficeId, SUM(CaseCount)AS Counts
FROM (
SELECT COUNT(C.CaseId) AS CaseCount,O.OfficeId
FROM [Case] C
INNER JOIN [Appointment] A ON C.CaseId = A.CaseId
INNER JOIN [Office] O ON A.OfficeId = O.OfficeId
WHERE C.DateCreated <= #BeginDate
AND C.CaseId NOT IN (SELECT CaseId FROM CaseStatusChange CSC WHERE CSC.DateClosed < #BeginDate)
--GROUP BY O.OfficeId
UNION
-- Also need the cases that reopened and are currently open
SELECT COUNT(ReOpened.CaseId) As CaseCount, ReOpened.OfficeID
FROM (
SELECT C.CaseId, MAX(CSC.DateReopened) AS DateReOpened, O.OfficeId
FROM [Case] C
INNER JOIN [CaseStatusChange] CSC ON C.CaseId = CSC.CaseId
INNER JOIN [Appointment] A ON C.CaseId = A.CaseId
INNER JOIN [Office] O ON A.OfficeId = O.OfficeId
WHERE CSC.DateReopened <= #BeginDate
--GROUP BY C.CaseId, O.OfficeID
) AS ReOpened
WHERE ReOpened.CaseId NOT IN
(
SELECT CaseId FROM CaseStatusChange
WHERE CaseId = ReOpened.CaseId AND
CaseStatusChange.DateClosed BETWEEN ReOpened.DateReopened AND #BeginDate
)
GROUP BY ReOpened.OfficeId
) AS OpenCasesCount
GROUP BY OfficeId
)
)
CaseOfficeAppointment
INNER JOIN [Case] C ON CaseOfficeAppointment.CaseId = C.CaseId
INNER JOIN [Office] O ON CaseOfficeAppointment.OfficeId = O.OfficeId
INNER JOIN [CaseType] CT ON C.CaseTypeId = CT.CaseTypeId
INNER JOIN [Court] CR ON C.CourtId = CR.CourtId
If I understood you right, you need something like :
CREATE PROCEDURE new_proc
AS
BEGIN
DECLARE #tmp_proc1 TABLE (// list all fields your first procedure returns );
DECLARE #tmp_proc2 TABLE (// list fields that your second SP returns);
INSERT INTO #tmp_proc1
EXECUTE Your_First_Procedure ;
INSERT INTO #tmp_proc2
EXECUTE Your_Second_Procedure;
// Finally, join data in #tmp_proc1 and #tmp_proc2
//(you probably need FULL JOIN) and return 1 resultset
END;
Provided you adjust the header to add all parameters needed, you can add as many result sets to a stored procedure as you need. Consuming the multiple tables will vary based on the language and platform you are using to consume the data, but simply result set from one sproc into the other should work fine, unless there is a limitation in the underlying data store (database server?).
ADDED:
Based on your response, you can combined the two results sets in a single stored procedure. To consume this, you have a variety of options. With a Reader, you can go to next result set, as it is a firehose cursor. But, it might be easier to use something like a DataSet and have it generated form the stored procedure. you can then use a table adapter to fill the data set from the stored procedure. Both tables should be filled now with a single call.
Does this make sense?

Resources