SQL: Adding time to Change Data Capture (CDC) Events

Several times now on forums, I've seen questions about Change Data Capture (CDC). People like the way they can retrieve details about changes that have occurred (often to trickle-feed into a data warehouse), but they are puzzled why CDC doesn't tell them when the event occurred. There's an easy fix for that.

Let's start by doing a quick CDC setup:

And let's then add three rows of data, then change one of them:

There are two ways we can see the changes:

That returns the following:

The first SELECT returns all changes as they occur, and the second SELECT returns the net affect of those changes. Because NewEmployeeID #1 was inserted as Fred Jones, and later changed to Greg Low, the net affect is just of an insert as Greg Low.

But notice, there's no time value. What we can use to get the time is the LSN (log sequence number) by calling the sys.fn_cdc_map_lsn_to_time() function like this:

Now that returns:

You can see that the function returns us the time. The time is in local time for the server.

If you want to tear the example back down, just do this:


Leave a Reply

Your email address will not be published. Required fields are marked *