我需要为已被跟踪的表向 CDC 添加几列。我的方法如下:
EXEC sys.sp_cdc_drop_job 'capture'
BEGIN TRANSACTION
BEGIN TRY
-- Copy existing data of the tracked table into a temporary table
SELECT * INTO CDC.dbo_MyTable_Temp FROM CDC.dbo_MyTable_CT
-- Add the new column to the temp table. This allows us to just use INSERT..SELECT * later
ALTER TABLE CDC.dbo_MyTable_Temp ADD MyColumn INT NULL
-- Disable CDC for the source table temporarily. This will drop the CDC table
EXEC sys.sp_cdc_disable_table @source_schema = 'dbo', @source_name = 'MyTable', @capture_instance = 'dbo_MyTable'
-- Reenable CDC for the source table. This will recreate the table with the new columns
EXEC sys.sp_cdc_enable_table @source_schema = 'dbo', @source_name = 'MyTable', @capture_instance = 'dbo_MyTable', @supports_net_changes = 1, @role_name = NULL, @filegroup_name = 'CDCGROUP'
-- Insert the old values into the CDC table
INSERT INTO cdc.dbo_MyTable_CT SELECT * FROM cdc.dbo_MyTable_Temp
-- Correct the start_lsn in CDC.change_tables. Otherwise all of the CDC stored procedures will be confused
-- and although the old data will exist in the table the functions won't return it
UPDATE cdc.change_tables SET start_lsn = (SELECT MIN(__$start_lsn) FROM cdc.dbo_MyTable_Temp) WHERE capture_instance = 'dbo_MyTable'
-- Drop the temp table
DROP TABLE cdc.dbo_MyTable_Temp
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
RAISERROR('Error!', 16, 1)
END CATCH
EXEC sys.sp_cdc_add_job 'capture'
但是,当该作业在重新添加后再次运行时,它会生成一个错误,表明违反了CDC.lsn_time_mapping
.
有什么建议么?
谢谢!