Skip to content

Instantly share code, notes, and snippets.

@billinkc
Created May 26, 2016 19:29
Show Gist options
  • Save billinkc/d1e9131395ec7d5fc689c78fd90c80ee to your computer and use it in GitHub Desktop.
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
-- 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