Search code examples
sql-serverchange-trackingsql-server-2019

How to store CHANGE_TRACKING_CURRENT_VERSION when using SQL Server Change Tracking?


I'm using Change Tracking in SQL Server (15) on a single table. My client application runs every x minutes and checks if the table data was changed to invalidate some cache. Within a single transaction, the client first obtains the current change tracking version (CHANGE_TRACKING_CURRENT_VERSION()), and then queries for changes compared to when the client previously ran. The client knows what the previous value of CHANGE_TRACKING_CURRENT_VERSION() was because it stores it's value in a separate table (of the same database) after a successful run. So when the client is done, the client overwrites the previous change tracking version with the current one.

To avoid invalidating the cache when nothing was changed, among other things the client checks if the change tracking version is larger than before. However, because the client stores the previous change tracking version in the database itself (which causes the version to increment), the current change tracking version will always be larger than the stored previous change tracking version.

For example, let's say the stored version is 5 and the current version is 6. The client will run and eventually overwrite the stored version with the current version. Now the stored value is 6, but because storing this value is considered a change by SQL Server Change Tracking, the current version of change tracking will become 7. On the next run, the client will again run (because 7 is larger than 6) and it will eventually overwrite the stored version with the current version again. It will go on like this forever.

Is there a way to solve this issue, without having to store the previous change tracking version in a different database?


Solution

  • It turns out I had mistakenly also enabled Change Tracking on the second table in which I was storing the previous change tracking version. This caused the issue I described. After realizing this and disabling Change Tracking on the table that didn't need it, I am no longer was having issues.