CREATE OR ALTER TRIGGER TR_Boletos_GerarCodigo
ON Boletos
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

    SELECT @UltimoNumero =
        ISNULL(
            MAX(
                CAST(
                    REPLACE(CODIGO, 'BO', '')
                AS INT)
            ),
        99)
    FROM Boletos
    WHERE CODIGO IS NOT NULL;

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