(整理)SQL Server 2008 CDC 功能使用

时间:2022-06-04 00:58:03

           最近某项目突然要增加数据的获取,但是不能改程序、也没有同步的只读库,只好使用CDC来进行尝试。

           CDC的启用和停止全部用SQL实现,在这里给出主要的SQL步骤:

           

/****** Script for SelectTopNRows command from SSMS  ******/
--------------------------------(1.1)启动数据库CDC
USE TestDB
GO
EXECUTE sys.sp_cdc_enable_db;
GO
--------------------------------(1.2)有错误15517则执行
ALTER AUTHORIZATION ON DATABASE::[TestDB] TO [sa]

---------------------------------(1.3)查看是否启用数据库CDC
SELECT  is_cdc_enabled,CASE WHEN is_cdc_enabled=0 THEN 'CDC功能禁用'ELSE 'CDC功能启用'END [描述]
FROM    sys.databases
WHERE   [name]='TestDB'

-------------------------------- (2.1)启动数据表CDC----
USE TestDB
GO
EXEC sys.sp_cdc_enable_table
    @source_schema= 'dbo',
    @source_name = 'TestTable',
    @role_name = NULL 
GO
----------------------------------(2.2)查看数据表CDC是否启用----
SELECT  name ,
        is_tracked_by_cdc ,
        CASE WHEN is_tracked_by_cdc = 0 THEN 'CDC功能禁用'
             ELSE 'CDC功能启用'
        END 描述
FROM    sys.tables
WHERE   OBJECT_ID= OBJECT_ID('TestTable')
----------------------------------(3)查询数据------
  SELECT TOP 1000 *  FROM [TestDB].[cdc].[dbo_TestTable_CT];--此表为默认生成
  
----------------------------------(4) 关闭表CDC----
USE TestDB
go
EXECUTE sys.sp_cdc_disable_table 
    @source_schema = 'dbo', 
    @source_name = 'TestTable',
    @capture_instance = 'dbo_TestTable'
go 

----------------------------------(5)关闭数据库CDC----
USE TestDB;
GO
EXECUTE sys.sp_cdc_disable_db;
GO

 参考文章:

 https://docs.microsoft.com/zh-cn/previous-versions/sql/sql-server-2008/bb510702(v=sql.100)

https://blog.csdn.net/yenange/article/details/49636215

https://blog.csdn.net/dba_huangzj/article/details/8130448

https://www.cnblogs.com/lyhabc/p/3383484.html