sqlserver 启用和查看更改跟踪
在SQL Server中,可以使用SQL Server Profiler工具或者T-SQL命令来启用和查看数据库的更改跟踪。以下是如何使用T-SQL命令来启用和查看数据库更改跟踪的步骤:
- 启用更改跟踪:
-- 启用数据库级别的更改跟踪
ALTER DATABASE YourDatabaseName
SET CHANGE_TRACKING = ON
(
AUTO_CLEANUP = ON,
CHANGE_RETENTION = 2 HOURS,
CLEANUP_JOB_HISTORY_RETENTION = 1 HOURS
)
-- 启用更改追踪的secondary角色
USE YourDatabaseName
EXEC sp_change_users_role 'YourUserName', 'db_owner';
- 启用跟踪特定表的更改:
-- 启用跟踪特定表的更改
USE YourDatabaseName
EXEC sys.sp_cdc_enable_table @source_schema = N'dbo', @source_name = N'YourTableName', @role_name = N'db_owner';
- 查看更改:
-- 查看指定表的更改
USE YourDatabaseName
GO
DECLARE @from_lsn binary(10), @to_lsn binary(10);
SET @from_lsn = sys.fn_cdc_get_min_lsn('YourTableName');
SET @to_lsn = sys.fn_cdc_get_max_lsn();
WITH CTE AS
(
SELECT
lsn,
operation,
[__$operation],
[id],
[name]
FROM
cdc.dbo_YourTableName_CT
WHERE
lsn BETWEEN @from_lsn AND @to_lsn
)
SELECT * FROM CTE;
请注意,在实际环境中,启用更改跟踪可能会对性能产生影响,并且需要数据库具备足够的资源来处理这些跟踪操作。在生产环境中应该谨慎使用。
评论已关闭