CREATE OR ALTER TRIGGER TR_Calibracao_GerarCodigo
ON Calibracao
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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