Search code examples
sql-serversql-server-2008-r2cdc

How to get the "start_lsn" value in application code


The database tracks all changes via the "Change Data Capture" mechanism. I need to add additional information about users who make these changes. The following users are not SQL Server users. Security authorization is performed via an outside mechanism.

I want to add a helper table with columns "start_lsn" and "userId" to associate a transaction with the authorized user. Is there any way to determine the "start_lsn" value, which corresponds to the current transaction executed in the application code?


Solution

  • At present, I have found the following solution:

    1)

    • Create one more table (for example, the "UserActivity"), which has the "ID" and "userId" columns;

    • Use the "ID" column as the Primary Key;

    • Enable the CDC option for this table.

    2)

    • Wrap all data modification operations with a transaction scope;

    • Add a new data record into this table with the current "userId" during a particular transaction:

      • Begin Exclusive Transaction;

      • Perform "Data Manipulation";

      • Insert Information about "userId" into the "UserActivity" table.

    Since the transaction is exclusive and all operations were made within a single transaction scope, the "last_lsn" ("start_lsn") value is the same.

    After that, using the JOIN operator, merge data from the "UserActivity" table with Data Manipulation information.