Guest User

audit reconstruction

a guest
Oct 1st, 2024
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.60 KB | Source Code | 0 0
  1. --set up dummy tables. These should match everywhere that's important
  2. declare @prodTable table (
  3.     UserID int,
  4.     AboutMe nvarchar(100)
  5. )
  6.  
  7. declare @testAudit table (
  8.     UserID int,
  9.     ChangeDate date,
  10.     AboutMe_Before varchar(100)
  11.  
  12. )
  13.  
  14. --either comment this or change the user ID to test 'row deleted' functionality
  15. insert into @prodTable (UserID, AboutMe) values
  16. (26837, 'This is not null'),
  17. (26838, 'abcde')
  18.  
  19. --note dates are different. I just need a little time difference in order to sort.
  20. --This assumption should hold for real auditing anyway - changes will be at different times
  21. insert into @testAudit (UserID, ChangeDate, AboutMe_Before) values
  22. (26837, '2024-01-01', '<p>I make Microsoft SQL Server etc etc'),
  23. (26838, '2024-01-02', 'original'),
  24. (26837, '2024-01-03', 'Update Numero Uno'),
  25. (26838, '2024-01-04', 'an update'),
  26. (26837, '2024-01-05', null);
  27.  
  28. --append the current value in the prod table as an 'audit' for each user id.
  29. --Also add an extra column - lastUpdate, so that the last row is not shown
  30. with a as (
  31.     select *, 0 as lastUpdate from @testAudit
  32.  
  33.     union
  34.  
  35.     select t.UserID,
  36.     getdate() as ChangeDate,
  37.     case when max(p.AboutMe) is null then 'row deleted' else max(p.AboutMe) end as AboutMe,
  38.     1 as lastUpdate
  39.     from @testAudit t
  40.     left join @prodTable p on t.UserID = p.UserID
  41.     group by t.UserID
  42. ),
  43.  
  44. --extra cte so the lead function doesn't cut off
  45. b as (
  46.     select
  47.     UserID,
  48.     ChangeDate,
  49.     AboutMe_Before,
  50.     lead(aboutMe_Before,1) over (partition by UserID order by changeDate) as AboutMe_After,
  51.     lastUpdate
  52.     from a
  53. )
  54.  
  55. --remove the last update
  56. select * from b where lastUpdate = 0
Advertisement
Add Comment
Please, Sign In to add comment