CREATE OR ALTER TRIGGER TR_Chamado_GerarCodigo
ON Chamado
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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