Following is inline table valued function
CREATE FUNCTION [dbo].[GetDipForDirectClientCharts]
(
@FacilityId AS UNIQUEIDENTIFIER ,
@PatientChartStatusCompleteEnum SMALLINT ,
@PatientChartLockingInterval SMALLINT
)
RETURNS TABLE
AS RETURN
(
WITH DirectPatientChartCTE
--Get all patient charts that qualify for dip criteria
AS ( SELECT TOP 500
VisitNumber,PatientChartID
FROM PatientChartCorporate WITH ( READPAST )
WHERE PatientChartCorporate.IsDeleted = 0
AND PatientChartCorporate.IsErroneous = 0
AND PatientChartCorporate.FacilityId = @FacilityId
AND ( DipFileName IS NULL
OR DipFileName = ''
)
AND PatientChartCorporate.ChartStatusID = @PatientChartStatusCompleteEnum
AND DATEDIFF(MINUTE, CompletedOn, GETUTCDATE()) >= +CONVERT(VARCHAR(30), @PatientChartLockingInterval)
AND ( PatientChartCorporate.CompletedOn IS NOT NULL )
),
RemotePatientChartCTE
AS ( SELECT TOP 500
VisitNumber,PatientChartID
FROM PatientCharts WITH ( READPAST )
WHERE PatientCharts.IsDeleted = 0
AND PatientCharts.IsErroneous = 0
AND PatientCharts.FacilityId = @FacilityId
AND ( DipFileName IS NULL
OR DipFileName = ''
)
AND PatientCharts.ChartStatusID = @PatientChartStatusCompleteEnum
AND DATEDIFF(MINUTE, CompletedOn, GETUTCDATE()) >= +CONVERT(VARCHAR(30), @PatientChartLockingInterval)
AND ( PatientCharts.CompletedOn IS NOT NULL )
)
SELECT PatientCharts.VisitNumber ,
PatientChartImages.ImageSequence AS ImageSequence
FROM dbo.PatientChartImagesCorporate AS PatientChartImages WITH ( READPAST )
INNER JOIN DirectPatientChartCTE AS PatientCharts ON PatientChartImages.PatientChartId = PatientCharts.PatientChartId
WHERE Patientchartimages.OnbasedDate IS NULL
UNION ALL
( SELECT PatientCharts.VisitNumber ,
PatientChartImages.ImageSequence AS ImageSequence
FROM dbo.PatientChartImages AS PatientChartImages WITH ( READPAST )
INNER JOIN RemotePatientChartCTE AS PatientCharts ON PatientChartImages.PatientChartId = PatientCharts.PatientChartId
WHERE Patientchartimages.OnbasedDate IS NULL
)
)
I have defined two CTE, DirectPatientChartCTE and RemotePatientChartCTE. I don’t want to use union all in case 0 records are returned by RemotePatientChartCTE.
I understand that I can use a where clause in query below union all to check for 0 records in CTE. In that case also second query will be evaluated. I don’t want tables in second query to be scanned in case records don’t exist.
This has been changed from a view to inline TVF since performance with a view was horrible. I cannot use a SP since I have to fill a dynamic temporary table with the results of this TVF. Please suggest.
You can turn your function into a multi statement table valued function. Execute the queries in your CTE’s one at a time and store the result from each query in a table variable each. Then you can check for row count in your second table variable and do the union query if necessary.
In pseudo code something like this.