SQL Server - Change Tracking (CT) - CodeProject

Articles » Database » Database » SQL Server

SQL Server - Change Tracking (CT)
By Chandra Sekhar - SQLVERSITY, 1 Feb 2013
5.00 (2 votes)

Have you ever tried to track the changes (DML changes like Insert, Delete and Update) which were done by you or your team members? If you have not, let’s play with the data by using one of the great features of SQL Server 2008.

Prior to SQL Server 2008, developers had to create some custom tracking solutions using DML Trigger and additional tables to track the data which we have modified. DML Triggers: These are the part of our transaction which contains the DML by which it is triggered. As we all know that, triggers are very expensive and we are using them in our transaction, the execution time will increase so that the performance of our project will be affected. Additional tables: By running the above DML triggers, we are able to track the data. But there is nothing to store these changes. To store this changed data, we need to create these additional tables. These tables will have similar columns as the tables which we need to track.

Takes much time to develop/create DML triggers and additional tables Performance hit Very complex process

SQL Server 2008
To overcome the above drawbacks, SQL Server 2008 introduced powerful and efficient tracking mechanisms called ‘Change Tracking (CT)’ and Change data Capture (CDC) In this article Change Data Capture (CDC) is out of scope. We may discuss about this in the coming articles. Note: Since I am a lazy fellow I am not going to say Change www.codeproject.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print tracking every time in this article. But I will just say 1/21


SQL Server - Change Tracking (CT) - CodeProject

Note: Since I am a lazy fellow I am not going to say Change tracking every time in this article. But I will just say CT. CT is a new feature in SQL Server 2008 which allows us to track information about changes that we have made to tables in which CT is enabled. When this is turned on for a table, it will keep track of each DML operation and the keys of the row that was affected. This means that at any time, we can query to find out which rows in our table(s) were inserted/deleted/updated.

DML Triggers and additional tables are no more required Efficient & fast Easy to track the data Minimal Disk Space Costs Packaged Functions available to query the data Auto Clean Up of side table data

Working with CT:
If we want to work with CT, we must enable CT on our database and tables on which we are interested to track the changes. We cannot enable CT for table without enabling CT for database. So should first enable CT for database and then for table. Before enabling, let us create a database ‘Change Tracking’ and a table ‘[dbo].[EmployeeTracking]’ and insert 10 rows into it.
-------------------------------------------- Cet Dtbs CagTakn - rae aaae hnercig -------------------------------------------UEmse S atr G O CET DTBS CagTakn RAE AAAE hnercig G O --------------------------------------------------------------------------------------- Cet tbe[b][mlyercig - rae al do.EpoeTakn] -------------------------------------------UECagTakn S hnercig G O CET TBE[b][mlyercig RAE AL do.EpoeTakn] ( EpoeI ITPIAYKY mlyeD N RMR E, EpoeNm Vrhr3) mlyeae aca(0, DsgainVrhr1) einto aca(5 ) --------------------------------------------------------------------------------------------------------- Isr 1 rcrsit [b][mlyercig tbe - net 0 eod no do.EpoeTakn] al -------------------------------------------------------------BGNTASCIN[T EI RNATO C] BGNTY EI R ISR [b][mlyercig VLE(,Bsai''AE) NET do.EpoeTakn] AUS1'iwjt,SS' ISR [b][mlyercig VLE(,Cad''AE) NET do.EpoeTakn] AUS2'hnu,SS'

ISR [b][mlyercig VLE (,Rkii,CE) NET do.EpoeTakn] AUS 3'umn''S'


Mhn.1 rw EET RM do.EpoeTakn] AUS 1.CE) NET do.codeproject.EpoeTakn] .AE) ISR [b][mlyercig VLE (.EpoeTakn] AUS 5'oa''S' ISR [b][mlyercig VLE (.EpoeTakn] AUS 7'rvn''S' ISR [b][mlyercig VLE(.EpoeTakn] AUS 4'hwa.AE) ISR [b][mlyercig VLE (.Ban''AE) NET do.0 os --------------------------------------------------- SQL Server .2/1/13 ISR [b][mlyercig VLE (.LS' NET do.EpoeTakn] AUS 6'tia.AE) NET do.EpoeTakn] AUS8'iami.Change Tracking (CT) .Rkii.Krna''S' NET do. www.EpoeTakn] AUS 3'umn''S' ISR [b][mlyercig VLE (.SS' ISR [b][mlyercig VLE (.CE) NET do.CodeProject Enabling CT for a database: Before enabling the CT.Lxa''CE) CMI TASCIN[T OMT RNATO C] EDTY N R BGNCTH EI AC RLBC TASCIN[T OLAK RNATO C] EDCTH N AC G O ---------------------------------------------------------------------------------------------------------------SLC *FO [b][mlyercig .Ngnr''CE) NET do.Ahr''S' NET do. By default CT is disabled.LS' ISR [b][mlyercig VLE (0'amn. let us check the properties of our database.Saai.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 3/21 .EpoeTakn] AUS 9'aeda.

4/21 .2/1/13 SQL Server .codeproject.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print master database.CodeProject Let us enable it by executing the following script.Change Tracking (CT) . But it is a best practice to run this in www. -------------------------------------------UEmse S atr G O ATRDTBS CagTakn LE AAAE hnercig STCAG_RCIG=O E HNETAKN N -------------------------------------------- We can run this in ALTER statement in Change Tracking database also.

if you make it 100 days. tracking data will be available for 100 days and older data will be removed automatically.UOCENP=O) E HNETAKN N CAG_EETO 0 ASAT_LAU N G O -------------------------------------------------------------------------- We can enable CT by using SQL Server Management Studio (SSMS) also. Note: Enabling from SSMS is not a good practice. Go to Object Explorer -> Databases -> Right click on your database -> Properties -> Change Tracking page -> set the values -> Ok. www.2/1/13 master database.CodeProject While enabling.Change Tracking (CT) .com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 5/21 .Let us enable it by executing the following script. SQL Server . CHANGE_RETENTION: This allows us to set the period for which tracking data should be stored. we can use the below two optional parameters. Suppose.codeproject. By default it is ON. let us check the properties of our table. Enabling CT for a table Before enabling the CT for our table. We can also set this value as per our requirement. AUTO_CLEANUP: It cleans the older data automatically if it is ON. By default it is 2 days. Ex: -------------------------------------------------------------------------UEmse S atr G O ATRDTBS CagTakn LE AAAE hnercig STCAG_RCIG=O (HNERTNIN=10DY. By default CT is disabled.

CodeProject -------------------------------------------UECagTakn S hnercig G O ATRTBE[b][mlyercig LE AL do.Change Tracking (CT) . we should run this under Change Tracking database not in master.EpoeTakn] EAL CAG_RCIG NBE HNETAKN -------------------------------------------- Since our table exists in Change Tracking database. TRACK_COLUMNS_UPDATED: This parameter is used to indicate the columns which are changed by UPDATE operation and also indicates that row has changed.2/1/13 SQL Server .codeproject. www. we can use the below optional parameter. While enabling.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 6/21 . By default. it is OFF.

[EmployeeTracking] table. Let’s track the data.OFF. Go to Object Explorer -> Databases ->Open your database ->Tables -> Right click on your table ->Properties > Change Tracking page -> set the values -> OK.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 7/21 . Now everything is ready. Operation 1 Delete one row from [dbo]. ------------------------------------------------DLT FO [b][mlyercig EEE RM do. By default.EpoeTakn] EAL CAG_RCIGWT (RC_OUN_PAE =OF NBE HNETAKN IH TAKCLMSUDTD F) G O --------------------------------------------------------- We can enable CT by using SQL Server Management Studio (SSMS) also.codeproject.2/1/13 operation SQL Server . (CT) . Example --------------------------------------------------------UECagTakn S hnercig G O ATRTBE[b][mlyercig LE AL do.EpoeTakn] WEEEpoeNm =Ban' HR mlyeae 'hwa ------------------------------------------------- Now the total numbers of rows are reduced to 9. www.Change Tracking it is CodeProject and also indicates that row has changed.

EpoeTakn] . ------------------------------------------------ISR [b][mlyercig NET do.2/1/13 SQL Server .Change Tracking (CT) .9rw EET RM do.EpoeTakn] VLE(1'rmgm.Auua''M) ------------------------------------------------- Now total number of rows is increased to 10.1 rw EET RM do.CodeProject ------------------------------------------------SLC *FO [b][mlyercig .EpoeTakn] os ------------------------------------------------- Operation 2 Insert one row into [dbo].0 os 8/21 .com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print ------------------------------------------------SLC *FO [b][mlyercig .E' AUS1.[EmployeeTracking] table.codeproject. www.

Like this make it ‘0’. you have done 5 modifications to the table. Then it should be 4.1 rw EET RM do. www. CHANGETABLE(): It is the mostly used CT function and which is used to obtain CT information of a table since the Tracking started. It is working like 5-4=1.2/1/13 SQL Server .0 os ------------------------------------------------- It is time to track the data. For example.EpoeTakn] .codeproject.CodeProject SLC *FO [b][mlyercig . Confused??? Please go through the below example. It retrieves only one record out of 5 records. List of functions used in CT: CHANGETABLE() CHANGE_TRACKING_CURRENT_VERSION() CHANGE_TRACKING_MIN_VALID_VERSION() CHANGE_TRACKING_IS_COLUMN_IN_MASK() WITH CHANGE_TRACKING_CONTEXT() 1. Second parameter will be PreviousSyncVersion which represents the number of changes to be retrieved since the CT started. but you want to track only recent (last) change.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 9/21 . Before tracking I would like to teach you guys about some built in functions of CT. if you want to retrieve all the changes made since the CT started.Change Tracking (CT) . It accepts two parameters. I think now you got how it is working. First parameter will be CHANGES+Tablename which need to be tracked.

2. CHANGE_TRACKING_CURRENT_VERSION(): It gives us the most recent value (version of last modification) of SYS_CHANGE_VERSION column.codeproject.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 10/21 . ------------------------------------------SLC CAG_RCIGCRETVRIN) EET HNETAKN_URN_ESO( ------------------------------------------- www.CodeProject Column Name Description SYS_CHANGE_VERSION It represents the last version number when a particular row was modified SYS_CHANGE_CREATION_VERSION It represents the version number when a record is inserted. This column will have values only when UPDATE operations are happened. <primary key columns> It represents the primary key columns of our tracked table.Delete U .Update SYS_CHANGE_COLUMNS It represents all the columns impacted since last baseline version. I . SYS_CHANGE_OPERATION The possible values of this column are I or D or U.2/1/13 SQL Server .Change Tracking (CT) .Insert D .

2/1/13 SQL Server . it is zero. It cannot be zero always. www.codeproject. It accepts one mandatory parameter which is the objectID of our table. But if you deal with more than one table. -----------------------------------------------------------------------------------------SLC CAG_RCIGMNVLDVRINOJC_D'mlyercig) A MnaiVrin EET HNETAKN_I_AI_ESO(BETI(EpoeTakn') S iVldeso ------------------------------------------------------------------------------------------ Note: You may get doubt that it is always 0.Change Tracking (CT) . Since you are only tracking the one table information.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 11/21 . it will be more than one. CHANGE_TRACKING_MIN_VALID_VERSION(): It gives the minimum change version number of a table after CT information is available or retained.CodeProject 3. The answer is No.

codeproject.2/1/13 tracking the one table information.mlyeD FO CAGTBECAGS[b][mlyercig. But if you deal with more than one table. around 5minutes back we did two changes to data in our table.)SE RM HNEAL(HNE do. CHANGE_TRACKING_IS_COLUMN_IN_MASK(): The value returned by SYS_CHANGE_COLUMNS column in CHANGETABLE function contains data in binary format. -----------------------------------------------------------SLC SSCAG_ESO.EpoeTakn]0A T ODRB SSCAG_ESO RE Y Y_HNEVRIN ------------------------------------------------------------ www.2rw EET RM HNEAL(HNE mlyercig0 S T os ----------------------------------------------------------------------- SQL Server .com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 12/21 .Change Tracking (CT) . If you remember. So let’s do some modification to the above query to display only required columns.Y_HNEOEAINEpoeI EET Y_HNEVRINSSCAG_PRTO.)A E . It takes two parameters. it will be more than one.e. it is zero.CodeProject In the above screenshot. WITH CHANGE_TRACKING_CONTEXT(): This function is used to differentiate between the changes you have made by your application and other applications. Now i am going to track those two records by using CHANGETABLE. 4. It is varbinary(128) and it do not accept NULL. First parameter is the table name and second parameter is the column name. ----------------------------------------------------------------------SLC *FO CAGTBECAGSEpoeTakn. It accepts one parameter called ‘context’ which is provided by the calling application and stored with tracking information. Note: Since the above two functions are not much useful in CT. One Delete and one Insert. This function is will return 1 or 0 depending on whether the column was updated or not. i. I am not going in deep. Because the tracking data of all tables is stored in CHANGETABLE only. we are having some columns which we do not want. 5.

it will throw the error. ---------------------------------------------------------UDT [b][mlyercig PAE do.codeproject.2/1/13 SQL Server .Change Tracking (CT) .EpoeTakn] STEpoeNm =Sata WEEEpoeNm =Rkii E mlyeae 'hnh' HR mlyeae 'umn' ---------------------------------------------------------- www. If you run the below statement. -----------------------------------------------------SLC *FO CAGTBECAGSEpoeTakn.CodeProject Note: Aliasing is mandatory while using CHANGETABLE.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 13/21 .) EET RM HNEAL(HNE mlyercig0 ------------------------------------------------------ Operation 3: Let’s update one of the records in our table.

3rw RE Y Y_HNEVRIN os ------------------------------------------------------------ www.Change Tracking (CT) .codeproject.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 14/21 .)SE EET RM HNEAL(HNE mlyercig0A T ODRB SSCAG_ESO .CodeProject --------------------------------------------------SLC *FO [b][mlyercig .2/1/13 SQL Server .EpoeTakn] .0 os --------------------------------------------------- -----------------------------------------------------------SLC *FO CAGTBECAGSEpoeTakn.1 rw EET RM do.

com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 15/21 .Change Tracking (CT) .2/1/13 SQL Server .CodeProject In the above example.0 os ----------------------------------------------------- www. But when we update non Primary key column.codeproject. CT works differently compare to when we update Primary key column. Please see the below example.EpoeTakn] STEpoeI =1 WEEEpoeI =7 E mlyeD 2 HR mlyeD ------------------------------------------- ----------------------------------------------------SLC *FO [b][mlyercig .EpoeTakn] .1 rw EET RM do. ------------------------------------------UDT [b][mlyercig PAE do. we updated Non Primary Key column.

But what if I want to see the data of all columns in our table? Can I get remaining columns data? www. The EmployeeID 7 is deleted and 12 are inserted in place of 7. --------------------------------------------------------------SLC *FO CAGTBECAGSEpoeTakn.codeproject.)A E EET RM HNEAL(HNE mlyercig0 S T ODRB SSCAG_ESO .Change Tracking (CT) .2/1/13 SQL Server .5rw RE Y Y_HNEVRIN os --------------------------------------------------------------- You may get one more doubt that he is showing only operation details whether it is Insert/Delete /Update.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 16/21 .CodeProject In this update statement. we are changing EmployeeID from 7 to 12.

Change Tracking (CT) . DsgainVrhr1) einto aca(5 ) ------------------------------------------- www.mlyeD ON do. my answer will be YES. I am creating a table called ‘[dbo]. it is displaying only Insert and Update data but not delete data. ------------------------------------------CET TBE[b][mlyercigoK RAE AL do.CodeProject If you observe the above data.)A E EET RM HNEAL(HNE do.[EmployeeTrackingNoPK]’.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 17/21 . But before closing I would like to discuss one hidden secret of CT. ----------------------------------------------------------------------SLC *FO CAGTBECAGS[b][mlyercig.EpoeTakn]0 S T JI [b][mlyercig A ETO ETEpoeI =E. Because these records are already deleted from our EmployeeTracking table. I think you got the solution to get those values. We should JOIN these two (CHANGETABLE and EmployeeTracking) based on EmployeeID.EpoeTaknNP] ( EpoeI IT mlyeD N. To explain this.2/1/13 But what if I want to see the data of all columns in our table? Can I get remaining columns data? If this is your question. Yes you are correct.mlyeD TEpoeI ----------------------------------------------------------------------- SQL Server . Clue: If you see in the above screenshot. We are almost done with CT. at last we have a column called EmployeeID which is the primary key of our EmployeeTracking table. EpoeNm Vrhr3) mlyeae aca(0.EpoeTakn] S T N T.codeproject.

Change tracking requires a primary key on the table.EpoeTaknNP] EAL CAG_RCIG NBE HNETAKN -------------------------------------------- Msg 4997. I tried to enable using SSMS also.Change Tracking (CT) . Line 1 Cannot enable change tracking on table 'EmployeeTrackingNoPK'. www. But no luck.codeproject. Create a primary key on the table before enabling change tracking.2/1/13 SQL Server . But it is throwing the below error L -------------------------------------------ATRTBE[b][mlyercigoK LE AL do.CodeProject Now I am trying to enable CT on this table. State 1.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 18/21 . Level 16.

After completion of Tracking we need to disable CT on our database and table.CodeProject I hope you guys got the hidden secret of CT. Otherwise we can’t enable CT.2/1/13 SQL Server . The secret is we can enable CT on a table when table is having Primary Key on it. We hope we are done with Tracking.EpoeTakn] DSBECAG_RCIG IAL HNETAKN G O ATRDTBS CagTakn LE AAAE hnercig STCAG_RCIG=OF E HNETAKN F G O --------------------------------------- www. ---------------------------------------.codeproject. We cannot disable CT for a database when CT is enabled on at least one table.ialn T ---------------------------------------ATRTBE[b][mlyercig LE AL do.Change Tracking (CT) . So first we need to disable in tables and then database.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 19/21 .DsbigC .

Since the first day of my IT career. Certification: Exam 70-433: Microsoft SQL Server 2008 R2.codeproject.5 years and have a good exposure on SQL Server 2008. along with any associated source code and files. is licensed under The Code Project Open License (CPOL) About the Author Chandra Sekhar . Database Development www. I learnt some advanced concepts in SQL server and I would like to share my knowledge to everyone. India for the last 2. So I started my blog by writing articles on SQL Server. As a part of my MCTS preparation.2/1/13 SQL Server . If you find any mistakes.SQLVERSITY Database Developer India Member Follow on Twitter Google I am working as a Senior Database developer in a reputed MNC located in Bangalore.com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 20/21 . License This article.CodeProject This is the first article in my life. I hope you guys enjoyed learning CT sorry Change Tracking. I have been interested in database. please let me know and we are always welcome to have suggestions from you to improve our future articles content quality. Based on your response very soon I may start writing tutorials and many more on SQL Server. I will catch you guys in my next article Change data Capture (CDC).Change Tracking (CT) .

com/Articles/537649/SQL-Server-Change-Tracking-CT?display=Print 21/21 .com/SQLVERSITY Google+: https://plus.CodeProject Exam 70-433: Microsoft SQL Server 2008 R2.SQLVERSITY Everything else Copyright © CodeProject.com Facebook: http://www. Permalink | Advertise | Privacy | Mobile Web02 | 2.codeproject.google. or click here to get a print view with messages.codeproject.com/SQLVERSITY Linkedin: http://www.facebook.com/in/sqlversity Twitter: https://twitter.13022.com/Articles/537649/SQLServer-Change-Tracking-CT to post and view comments on this article.6.Change Tracking (CT) . 1999-2013 Terms of Use www.com/u/0/110655723589368037929/ Comments and Discussions 1 message has been posted for this article Visit http://www. Database Development Blog: http://sqlversity.2/1/13 SQL Server .linkedin.3 | Last Updated 1 Feb 2013 Article Copyright 2013 by Chandra Sekhar .wordpress.

Sign up to vote on this title
UsefulNot useful