return: text
lang: plpgsql
src: |
  DECLARE result TEXT;
  BEGIN
  	-- Table des ages à créer
  	DROP TABLE IF EXISTS w_tmp;
  	
  	CREATE TEMP TABLE w_tmp AS
  		SELECT 
  			t_ages.oid,
  			t_ages.code,
  			t_ages.texte
  		FROM base.t_ages
  		ORDER BY code;
  
  	-- Remise bon oid (en deux étapes pour éviter clés en double)
  	UPDATE 
  		activite.t_ages_c
  	SET 
  		oid = 0 - w_tmp.oid
  	FROM 
  		w_tmp
  	WHERE 
  		t_ages_c.code = w_tmp.code
  		AND (
  				t_ages_c.oid <> w_tmp.oid
  			);
  
  	UPDATE 
  		activite.t_ages_c
  	SET 
  		oid = w_tmp.oid
  	FROM 
  		w_tmp
  	WHERE 
  		t_ages_c.code = w_tmp.code
  		AND (
  				t_ages_c.oid <> w_tmp.oid
  			);
  
  	-- Mise à jour codes selon base
  	UPDATE 
  		activite.t_ages_c
  	SET 
  		code = w_tmp.code,
  		texte = w_tmp.texte
  	FROM 
  		w_tmp
  	WHERE 
  		t_ages_c.oid = w_tmp.oid
  		AND (
  				t_ages_c.code IS DISTINCT FROM w_tmp.code
  				OR t_ages_c.texte IS DISTINCT FROM w_tmp.texte
  			);
  
  	-- Ajout nouveaux codes
  	INSERT INTO activite.t_ages_c (
  		oid,
  		code,
  		texte
  		)
  	SELECT w_tmp.oid,
  		w_tmp.code,
  		w_tmp.texte
  	FROM w_tmp
  	WHERE w_tmp.oid NOT IN (
  			SELECT oid
  			FROM activite.t_ages_c
  			)
  	ORDER BY w_tmp.code;
  	
  	RETURN 'OK';
  END;