CREATE OR ALTER TRIGGER TR_Despesas_GerarCodigo
ON Despesas
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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