CREATE OR ALTER TRIGGER TR_CalibracaoPadrao_GerarCodigo
ON Calibracao_Padrao
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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