view the changed values after an update statement

落花浮王杯 提交于 2019-12-13 03:31:27

问题


just wondering if it is possible to view the changes of an update command on a table after it has happened?

would the transaction log store this kind of information i.e this is the previous/current value this is the new/changed value

not sure if this is possible. the server is ms sql 2008


回答1:


The transaction log does contain the information, although decoding it is not trivial - I wrote a blog post with an example of decoding a simple update statement in the transaction log - http://sqlfascination.com/2010/02/21/decoding-a-simple-update-statement-within-the-transaction-log/

However, depending on the update being performed the entries in the log get a lot more complex and there is no documentation available on how to decode them. Reverse engineering them is quite difficult.

I would never recommend that this technique of inspecting the log is used to retrieve data, it is only worth looking into from an internals learning perspective / forensic perspective.




回答2:


you can use OUTPUT to insert the changes into another table and/or return a result set of the changes:

set nocount on
DECLARE @Table     table (PK int, col1 varchar(5))
DECLARE @SavedPks  table (PK int)

INSERT INTO @Table VALUES (1,'g')
INSERT INTO @Table VALUES (2,'g')
INSERT INTO @Table VALUES (3,'g')
INSERT INTO @Table VALUES (4,'g')
INSERT INTO @Table VALUES (5,'x')
INSERT INTO @Table VALUES (6,'x')
set nocount off

UPDATE @Table
    SET col1='xyz'
    OUTPUT INSERTED.PK INTO @SavedPks --save in a table
    OUTPUT 'result set',INSERTED.PK, INSERTED.col1 AS new_col1, DELETED.col1 AS old_Col1 --result set
    WHERE col1='g'

select * from @Table
select * from @SavedPks

OUTPUT:

           PK          new_col1 old_Col1
---------- ----------- -------- --------
result set 1           xyz      g
result set 2           xyz      g
result set 3           xyz      g
result set 4           xyz      g

(4 row(s) affected)

PK          col1
----------- -----
1           xyz
2           xyz
3           xyz
4           xyz
5           x
6           x

(6 row(s) affected)

PK
-----------
1
2
3
4


来源:https://stackoverflow.com/questions/7599276/view-the-changed-values-after-an-update-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!