I have an AuditDB table that tracks all changes to the DB. Cols like:
ID, TableName, OldVal, NewVal, UpdateDate
I have a 2nd table that tracks user logins.
Cols:
ID, UserName, LoginDT
The tables can't be simply joined on Timestamp. I'd like to return the AuditDB cols and the UserName of the person logged in most recently to the time the row was updated. That is, the UserName of the person most likely to have made the DB change!
I might be close, but this statement won't work because I have 'ddiff' as a 2nd column in my subquery, but I don't know how else to do the calculation.
ID, TableName, OldVal, NewVal, UpdateDate
I have a 2nd table that tracks user logins.
Cols:
ID, UserName, LoginDT
The tables can't be simply joined on Timestamp. I'd like to return the AuditDB cols and the UserName of the person logged in most recently to the time the row was updated. That is, the UserName of the person most likely to have made the DB change!
I might be close, but this statement won't work because I have 'ddiff' as a 2nd column in my subquery, but I don't know how else to do the calculation.
Code:
SELECT db.[AuditID]
,db.[Type]
,db.[TableName]
,db.[PK]
,db.[FieldName]
,db.[OldValue]
,db.[NewValue]
,(SELECT TOP(1) UserName, DATEDIFF(hh, LoginDT,db.[UpdateDate])AS ddiff FROM Audit_LoggedIn ORDER BY ddiff)
,db.[UpdateDate]
FROM [Audit_DB] db
WHERE db.[UpdateDate] BETWEEN @StartDateTime AND @EndDateTime
ORDER BY db.[UpdateDate] desc