Is there a better way to write this query:
INSERT INTO #Temp (MinDateTime, VehicleID)
SELECT Min(CAST(RDate AS smalldatetime) + RTime) as MinDateTime, T.VehicleID
FROM (
SELECT D.RDate, D.RTime, D.VehicleID
FROM DELETED AS D
JOIN INSERTED AS I ON D.ReceiptID = I.ReceiptID
AND (D.[RDate] <> I.[RDate] OR D.[RTime] <> I.[RTime] OR D.VehicleID <> I.VehicleID OR D.Liters <> I.Liters OR D.OdometerReading <> I.OdometerReading)
UNION ALL
SELECT I.RDate, I.Rtime, I.VehicleID
FROM INSERTED AS I
JOIN DELETED AS D ON I.ReceiptID = D.ReceiptID
AND (I.[RDate] <> D.[RDate] OR I.[RTime] <> D.[RTime] OR I.VehicleID <> D.VehicleID OR I.Liters <> D.Liters OR I.OdometerReading <> D.OdometerReading)
UNION ALL
SELECT D.RDate, D.RTime, D.VehicleID
FROM DELETED AS D
LEFT JOIN INSERTED AS I ON D.ReceiptID = I.ReceiptID
WHERE I.ReceiptID IS NULL
UNION ALL
SELECT I.RDate, I.Rtime, I.VehicleID
FROM INSERTED AS I
LEFT JOIN DELETED AS D ON I.ReceiptID = D.ReceiptID
WHERE D.ReceiptID IS NULL
) AS T
GROUP BY T.VehicleID
ORDER BY MinDateTime, T.VehicleID
This is part of an after update trigger that evaluates records who have been deleted/added/inserted and looks at one of the 5 columns if they’ve been modified it generates a list of vehicles and date/time so that the trigger can execute a stored proc that recalculates affected records.
I suspect the inner query could be written as:
In other words, I replaced the sequence of unions with a
full outer joinand then put all the conditions together in awhereclause, separated byors.