CREATE OR ALTER TRIGGER TR_ContasContas_GerarCodigo
ON Contas_contas
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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