CREATE OR ALTER TRIGGER TR_CalibracaoPadraoEnsaios_GerarCodigo
ON Calibracao_Padrao_ensaios
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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