CREATE OR ALTER TRIGGER TR_ConvenioBoletos_GerarCodigo
ON Convenio_boletos
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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