CREATE OR ALTER TRIGGER TR_Contas_GerarCodigo
ON Contas
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

    SELECT
        @UltimoNumero =
        ISNULL(
            MAX(
                TRY_CAST(CODIGO AS INT)
            ),
        99)
    FROM Contas
    WHERE ISNUMERIC(CODIGO) = 1;

    ;WITH Numerados AS
    (
        SELECT
            ID_CONTAS,
            ROW_NUMBER() OVER
            (
                ORDER BY ID_CONTAS
            ) AS Linha
        FROM inserted
    )
    UPDATE C
    SET
        CODIGO =
        CAST(
            @UltimoNumero + N.Linha
        AS VARCHAR)
    FROM Contas C
    INNER JOIN Numerados N
        ON C.ID_CONTAS = N.ID_CONTAS;
END
GO