CREATE OR ALTER TRIGGER TR_Cartoes_GerarCodigo
ON Cartoes
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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