Ledger - SQL Server

In SQL Server 2022, the Ledger feature is a new addition that provides a built-in way to track and audit changes to data in a database. The Ledger feature maintains a complete history of all changes made to specified tables, including inserts, updates, and deletes, and allows you to easily view and analyze this history to track changes and identify issues.

To use the Ledger feature, you first need to enable it on a database by setting the "IS_LEADGER_ENABLED" database configuration option to "ON". Once this is done, you can then specify which tables you want to track using the "ALTER TABLE" command with the "WITH (SYSTEM_VERSIONING = ON)" option.

For example, the following command enables the Ledger feature for a table named "Customer" in a database named "Sales":

ALTER TABLE [Sales].[dbo].[Customer] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[CustomerHistory]));

This will enable the Ledger feature for the "Customer" table and create a new history table named "CustomerHistory" to store the history of all changes to the table.

Once the Ledger feature is enabled for a table, you can use the "FOR SYSTEM_TIME" clause in queries to view the history of changes to the table. For example, the following query retrieves all rows from the "Customer" table as they existed on a specific date:

SELECT * FROM [Sales].[dbo].[Customer] FOR SYSTEM_TIME AS OF '2022-02-15 00:00:00.000';

This will return all rows from the "Customer" table as they existed on February 15th, 2022, based on the history tracked by the Ledger feature.

You can also use the "CHANGES" function to retrieve a list of changes made to a table over a specific period of time. For example, the following query retrieves all changes made to the "Customer" table in the past day:

SELECT * FROM [Sales].[dbo].[Customer] FOR SYSTEM_TIME FROM '2022-02-14 00:00:00.000' TO '2022-02-15 00:00:00.000' WHERE CHANGES() IS NOT NULL;

This will return all rows from the "Customer" table that were changed between February 14th and February 15th, 2022, based on the history tracked by the Ledger feature.

The Ledger feature in SQL Server 2022 provides a powerful way to track and audit changes to data in a database, and can be useful for compliance, auditing, and troubleshooting purposes. By enabling the Ledger feature and using the appropriate queries, you can easily view and analyze the history of changes to tables in a database and track data changes over time.

Note - Because the ledger feature cannot be turned off, you must plan your storage requirements accordingly.




Comments

Popular posts from this blog

COPILOT Feature in SQL Server 2025

Prefetching - SQL Server

Split Brain - SQL Server