0

有没有更好的方法来编写这个查询:

    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 列中的一列是否已被修改,它会生成车辆列表和日期/时间,以便触发器可以执行重新计算受影响记录的存储过程。

4

1 回答 1

1

我怀疑内部查询可以写成:

    SELECT D.RDate, D.RTime, D.VehicleID
    FROM DELETED D full outer JOIN
         INSERTED I
         ON D.ReceiptID = I.ReceiptID
    where ((D.[RDate] <> I.[RDate] OR D.[RTime] <> I.[RTime] OR D.VehicleID <> I.VehicleID OR D.Liters <> I.Liters OR D.OdometerReading <> I.OdometerReading) or
           (I.[RDate] <> D.[RDate] OR I.[RTime] <> D.[RTime] OR I.VehicleID <> D.VehicleID OR I.Liters <> D.Liters OR I.OdometerReading <> D.OdometerReading) or
         I.ReceiptID IS NULL or
         D.ReceiptID IS NULL
        ) and
        (coalesce(i.ReceiptId, d.receiptId) is not null)  -- check that at least one has a value

换句话说,我用 a 替换了联合序列,full outer join然后将所有条件放在一个where子句中,用 s 分隔or

于 2012-12-09T16:27:19.703 回答