CREATE OR ALTER TRIGGER TR_ClientesEnderecos_GerarCodigo
ON Clientes_enderecos
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @UltimoNumero INT;

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

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