CREATE OR ALTER TRIGGER TR_Chegues_GerarCodigo
ON Chegues
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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