如何跟踪SQL Server中的记录更改?

时间:2017-04-07 05:42:37

标签: sql sql-server sql-server-2012

我有下表,其中包含所有学生的跟踪记录。

|==========================================|
| ID      |  Department     | Date         |
|==========================================|
| 001     | English         | Feb 3 2017   |
| 001     | English         | Feb 4 2017   |
| 001     | Science         | Mar 1 2017   |
| 001     | Science         | Apr 2 2017   |
| 001     | Maths           | Apr 7 2017   |
| 002     | Maths           | Feb 1 2017   |
| 002     | Maths           | Apr 7 2017   |
| 003     | Maths           | Apr 3 2017   |
| 004     | Science         | Feb 1 2017   |
| 004     | Maths           | Apr 7 2017   |
|==========================================| 

我需要在学生更换部门之前获取之前的记录。对于上面的示例,返回的记录集应为

对于001,

| 001     | English         | Feb 4 2017   |
| 001     | Science         | Apr 2 2017   |

适用于002和003

无变化

004

| 004     | Science         | Feb 1 2017   |

同一用户也可能会更改回同一个部门。例如,user001可以从dept a更改为dept b更改为dept c并返回dept a。我读过有关T-SQL发送和接收的内容。但不确定这在这种情况下是否会有所帮助。请帮忙。

3 个答案:

答案 0 :(得分:3)

一种方法是使用ROW_NUMBER函数进行分区,以检测Department列的值何时发生变化。

示例数据

DECLARE @T TABLE (ID int, Department nvarchar(100), dt date);
INSERT INTO @T (ID, Department, dt) VALUES
(1, 'English', 'Feb 3 2017'),
(1, 'English', 'Feb 4 2017'),
(1, 'Science', 'Mar 1 2017'),
(1, 'Science', 'Apr 2 2017'),
(1, 'Maths  ', 'Apr 7 2017'),
(2, 'Maths  ', 'Feb 1 2017'),
(2, 'Maths  ', 'Apr 7 2017'),
(3, 'Maths  ', 'Apr 3 2017'),
(4, 'Science', 'Feb 1 2017'),
(4, 'Maths  ', 'Apr 7 2017');

<强>查询

WITH
CTE
AS
(
    SELECT
        ID
        ,Department
        ,dt
        ,ROW_NUMBER() OVER (PARTITION BY ID, Department ORDER BY dt DESC) AS rnPart
        ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY dt DESC) AS rnID
    FROM @T
)
SELECT
    ID
    ,Department
    ,dt
FROM CTE
WHERE
    rnPart = 1
    AND rnID <> 1
ORDER BY
    ID
    ,dt
;

<强>结果

+----+------------+------------+
| ID | Department |     dt     |
+----+------------+------------+
|  1 | English    | 2017-02-04 |
|  1 | Science    | 2017-04-02 |
|  4 | Science    | 2017-02-01 |
+----+------------+------------+

答案 1 :(得分:1)

这可以通过在需要跟踪的表上创建插入/更新触发器来完成。使用逻辑表在sql server中插入/删除,您可以跟踪表上新插入和修改的字段。

已插入(逻辑表):它将为您提供新插入的记录/更新值(列值)的详细信息。

已删除(逻辑表):它会在修改/删除之前为您提供字段的旧值。

答案 2 :(得分:0)

I'm not that sure about it but you can get help with the concept of stored procedures. They are functions which are a part of database. You can set the display when you make the query