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に置き換えてから、すべての条件をsで区切って句にfull outer joinまとめました。whereor

于 2012-12-09T16:27:19.703 に答える