CREATE OR ALTER TRIGGER TR_ContasDepositos_GerarCodigo
ON Contas_depositos
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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