Eric
Eric

Reputation: 11662

change-data-capture from many tables via a single stored procedure?

I need to retrieve change-data-capture rows for several tables, and I'm required (by company IT policy) to access the database via stored procedures. I would rather create a single stored procedure with the table name as a parameter, rather than one stored procedure for each table I'm monitoring. Where I get hung up is that CDC defines a separate table-valued function name for each table monitored, and I'm not sure how best to generalize around that.

Is it possible to modify the following example code so that it invokes cdc.fn_cdc_get_net_changes_dbo_ + @Table instead of cdc.fn_cdc_get_net_changes_dbo_TABLE ?

Is there another approach I should use?

create proc [dbo].GetChangesForTable
 @Table varchar(50),
 @BeginTime datetime,
 @EndTime datetime
as
begin

    DECLARE @begin_lsn binary(10), @end_lsn binary(10); 
    DECLARE @func nvarchar(128)

    if @EndTime is null select @EndTime=GETDATE()

    SELECT @begin_lsn = sys.fn_cdc_map_time_to_lsn('smallest greater than', @BeginTime); 
    SELECT @end_lsn = sys.fn_cdc_map_time_to_lsn('largest less than or equal', @EndTime); 

     -- HOW TO GET THE CORRECT FUNCTION CALLED HERE?        
    SELECT * FROM cdc.fn_cdc_get_net_changes_dbo_TABLE(@begin_lsn, @end_lsn, 'all')

end
GO

Upvotes: 0

Views: 1594

Answers (1)

Michaël
Michaël

Reputation: 6734

I think that's possible with sp_executesql like that :

DECLARE @sql nvarchar(4000)
    SET @sql = N'SELECT * FROM cdc.fn_cdc_get_net_changes_dbo_'+cast(@TABLE as varchar)+'(@begin_lsn, @end_lsn, 'all')'


EXEC sp_executesql @sql, N'@Table varchar(50), @BeginTime datetime, @EndTime datetime',@Table,@BeginTime,@EndTime

Upvotes: 0

Related Questions