这是我的表表。
MeterID int
LatestMeterReadingID int refers MeterReadingMeterReadingTable
MeterID int
MeterReadingID int
Reading bigint
ForDate date
isInactive bit我希望在表表上设置一个触发器,以便在更新/插入表时将最新的表读数放在表上。
如果日期相等的话,我也想要更高的读数。
我已经通过ORM完成了这个任务,但是我希望将这个逻辑转移到数据库中。我可以做它的插入部分,但不确定如何处理更新。
最上面的意思是这个
Where isInactive=0 Order By ForDate DESC, Reading DESC发布于 2015-06-30 05:53:52
我想这就是你需要的。它可能需要一些调整:
CREATE TRIGGER dbo.MeterReadingTrigger
ON dbo.MeterReading
AFTER INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON;
;WITH cte AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY MeterID ORDER BY MeterID, ForDate DESC, Reading DESC) AS Row,
mr.MeterID,
mr.MeterReadingID,
mr.Reading,
mr.ForDate,
mr.IsInactive
FROM
dbo.MeterReading AS mr
JOIN Inserted i ON mr.MeterId = i.MeterID
WHERE
mr.IsInactive = 0
)
UPDATE m
SET m.LatestMeterReadingId = cte.MeterReadingId
FROM
cte JOIN
INSERTED i
ON cte.MeterID = i.MeterId
JOIN Meter m
ON m.MeterID = i.MeterId
WHERE
Row = 1
END
GO使用插入到CTE中的联接更新应答。
https://stackoverflow.com/questions/31128313
复制相似问题