我们通过创建单独的数据库表来创建单独的数据库表,其中包含我们想要快照的数据,但是非规范化,即每个记录都包含所有需要理解的数据,而不是引用可能存在或可能不再存在的id.它还为每行添加了一个日期.
然后,我们为特定的插入或更新生成了对所有受影响的表进行连接的触发器,并将其插入到快照表中.
这样一来,写一些将用户数据恢复到一个时间点的东西就是微不足道的.
如果你有一张桌子:
用户:
id, firstname, lastname, department_id
部:
id, name, departmenthead_id
您的用户表的快照可能如下所示:
user_id, user_firstname, user_lastname, department_id, department_name, deparmenthead_id, deparmenthead_firstname, departmenthead_lastname, snapshot_date
和一个查询
INSERT INTO usersnapshot
SELECT user.id AS user_id, user.firstname AS user_firstname, user.lastname AS user_lastname,
department.id AS department_id, department.name AS department_name
departmenthead.id AS departmenthead_id, departmenthead.firstname AS departmenthead_firstname, departmenthead.lastname AS departmenthead_lastname,
GETDATE() AS snapshot_date
FROM user
INNER JOIN department ON user.department_id = department.id
INNER JOIN user departmenthead ON department.departmenthead_id = departmenthead.id
这可以确保快照中的每一行在时间上都是正确的,即使部门或部门主管同时发生变化.