这是我的 Meter 表。
MeterID int
LatestMeterReadingID int refers MeterReading
MeterReadingTable
MeterID int
MeterReadingID int
Reading bigint
ForDate date
isInactive bit
我想在仪表读数表上设置一个触发器,在更新/插入时将最新的仪表读数放在仪表上
如果日期相同,我也想要更高的抄表。
我是通过我的ORM完成此操作但想将此逻辑传输到数据库。我可以插入它的一部分,但不知道如何处理更新。
最顶层我的意思是
Where isInactive=0 Order By ForDate DESC, Reading DESC
答案 0 :(得分:0)
我认为这就是你所需要的。可能需要一些调整:
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中加入INSINED来更新答案。