Created
May 26, 2016 19:29
-
-
Save billinkc/d1e9131395ec7d5fc689c78fd90c80ee to your computer and use it in GitHub Desktop.
Trigger rewrite based on https://twitter.com/vongillern/status/735908622677475328 Approximately correct, actual correctness left to the implementer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Really, what you want is probably something like | |
INSERT INTO | |
MeterAudit | |
( | |
MeterAuditId, MeterId, PreviousAuditId /*...*/ | |
) | |
-- Find the last/most recent entry in MeterAudit for all the things we just changed | |
SELECT | |
NEWID() AS MeterAuditId, I.MeterId, MA.PreviousAuditId /*...*/ | |
FROM | |
Inserted AS I | |
-- LEFT because they might not have had an entry before | |
LEFT OUTER JOIN | |
MeterAudit MA | |
ON MA.MeterId = I.MeterId | |
-- Correlated subquery to find the most recent audit date | |
AND MA.AuditDate = | |
( | |
SELECT | |
MAX(MAI.AuditDate) | |
FROM | |
dbo.MeterAudit AS MAI | |
WHERE | |
MA.MeterId = I.MeterId | |
) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment