SQL Server: How to list changed columns with change tracking?

北城余情 提交于 2021-01-27 06:29:19

问题


I use SQL Server 2012 Standard edition, and I activated Change Tracking function on a table.

When I list changes on a table with the CHANGETABLE function, I have a SYS_CHANGE_COLUMNS property with binary data

0x0000000045000000460000004700000048000000

How do I know which columns have changed ?


回答1:


Because the column is a bitmask made up of the column IDs of all the columns which were changed, it's difficult to know what it's made up of. In fact, MSDN says not to interrogate SYS_CHANGE_COLUMNS directly here: https://msdn.microsoft.com/en-us/library/bb934145.aspx

This binary value should not be interpreted directly.

However, when you are detecting changes for notification purposes, usually the notification consumer has a good idea of which columns they are interested in changing.

For this use-case, use the CHANGE_TRACKING_IS_COLUMN_IN_MASK function.

-- Get the column ID of my column
declare @MyColumnId int
set @MyColumnId = columnproperty(object_id('MyTable'), 'MyColumn', 'ColumnId')

-- Check if it's changed
declare @MyColumnHasChanged bit
set @MyColumnHasChanged = CHANGE_TRACKING_IS_COLUMN_IN_MASK (MyColumnId, @change_columns_bitmask);  

If CHANGE_TRACKING_IS_COLUMN_IN_MASK tell me if a column has changed, how can I write a script that tell me which columns have changed ? I have around 50 attributes for each table.

I'm afraid you'll need to loop through all of the columns you may be interested in... If this is too restrictive, you may have to use another change-notification approach, like Change Data Capture (CDC), or Triggers



来源:https://stackoverflow.com/questions/40674192/sql-server-how-to-list-changed-columns-with-change-tracking

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