このクエリを書くためのより良い方法はありますか?
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
これは、削除/追加/挿入されたレコードを評価し、変更されている場合は5つの列のいずれかを確認する更新後トリガーの一部であり、トリガーが実行できるように車両と日付/時刻のリストを生成します。影響を受けるレコードを再計算するストアドプロシージャ。