CREATE OR ALTER TRIGGER TR_ConvenioCartoes_GerarCodigo
ON Convenio_cartoes
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

    SELECT
        @UltimoNumero =
        ISNULL(
            MAX(
                TRY_CAST(
                    REPLACE(CODIGO, 'CC', '')
                AS INT)
            ),
        99)
    FROM Convenio_cartoes
    WHERE CODIGO LIKE 'CC%';

    ;WITH Numerados AS
    (
        SELECT
            ID_CONV_CARTOES,
            ROW_NUMBER() OVER
            (
                ORDER BY ID_CONV_CARTOES
            ) AS Linha
        FROM inserted
    )
    UPDATE C
    SET
        CODIGO =
            'CC' +
            RIGHT(
                '0000' +
                CAST(
                    @UltimoNumero + N.Linha
                AS VARCHAR
                ),
            4)
    FROM Convenio_cartoes C
    INNER JOIN Numerados N
        ON C.ID_CONV_CARTOES =
           N.ID_CONV_CARTOES;
END
GO