Is there any way to get only column names where we have modified values in CDC table?

  Kiến thức lập trình
DECLARE @ColumnName NVARCHAR(MAX);
DECLARE @SQLQuery NVARCHAR(MAX) = N'';
DECLARE @HasColumns BIT = 0;

DECLARE ColumnCursor CURSOR FOR
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'dbo_OINV_CT' AND TABLE_SCHEMA = 'cdc'; -- Adjust the schema name if necessary

OPEN ColumnCursor;
FETCH NEXT FROM ColumnCursor INTO @ColumnName;

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @HasColumns = 0
    BEGIN
        SET @SQLQuery = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE 1=0 ';
        SET @HasColumns = 1;
    END

    SET @SQLQuery = @SQLQuery +
        'OR EXISTS (
            SELECT 1
            FROM cdc.dbo_OINV_CT t1
            INNER JOIN cdc.dbo_OINV_CT t2 ON t1.__$start_lsn = t2.__$start_lsn AND t1.__$seqval = t2.__$seqval
            WHERE t1.[__$operation] = 3 -- Before update
            AND t2.[__$operation] = 4 -- After update
            AND t1.' + QUOTENAME(@ColumnName) + ' <> t2.' + QUOTENAME(@ColumnName) + '
        )' + CHAR(13);

    FETCH NEXT FROM ColumnCursor INTO @ColumnName;
END

CLOSE ColumnCursor;
DEALLOCATE ColumnCursor;



-- Execute the constructed SQL query if columns are found
IF @HasColumns = 1
BEGIN
    SET @SQLQuery = REPLACE(@SQLQuery, 'OR EXISTS', 'AND (EXISTS');
    SET @SQLQuery = REPLACE(@SQLQuery, ' OR)', ')');
    EXEC sp_executesql @SQLQuery;
END
ELSE
BEGIN
    PRINT 'No columns found in dbo_OINV_CT.';
END

Trying to get only column names where we modified values from CDC table, script is not completely executed.

Error:Msg 191, Level 15, State 1, Line 1712Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.

New contributor

user23544169 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT