以下是內聯表值函數如何在表值函數中使用條件聯合ALL?
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
)
)
我定義了兩個CTE,DirectPatientChartCTE
和RemotePatientChartCTE
。如果0記錄由RemotePatientChartCTE
返回,我不想使用union。
據我所知,我可以在查詢下使用union子語中的where子句來檢查CTE中的0條記錄。在這種情況下,第二個查詢也會被評估。如果記錄不存在,我不希望第二個查詢中的表進行掃描。
這已經從一個視圖更改爲內聯TVF,因爲視圖的性能很糟糕。我不能使用SP,因爲我必須用這個TVF的結果填充動態臨時表。請建議。
當查詢中的其中一個表要返回0行,並且INNER JOIN連接到查詢中的其他表時,則應該發生其他表的「實際」掃描,假設優化器可以很好地完成工作,並且索引是合適的。生成0結果通常是一種快速操作。 –