有没有更好的方法来编写这个查询:
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 列中的一列是否已被修改,它会生成车辆列表和日期/时间,以便触发器可以执行重新计算受影响记录的存储过程。