return: text
lang: plpgsql
src: |
  DECLARE	
  	
  BEGIN
  	INSERT INTO pmsi.t_divers (code, texte, valeur, description)
  	SELECT
  		'PURGE_IMPORT',
  		'Purge des imports (IN,OUT). Nombre d''annees a conserver',
  		'99',
  		'Purge des imports (IN,OUT). Nombre d''annees a conserver (le dernier mois de chaque annee est conserve)'
  	WHERE 'PURGE_IMPORT' NOT IN (SELECT code FROM pmsi.t_divers)
  	; 
  
  	DROP TABLE IF EXISTS w_periode;
  	CREATE TEMP TABLE w_periode AS 
  	SELECT date(date_trunc('year',now())-(valeur||' years')::interval+interval '1 year'-interval '1 day') AS date_purge
  	FROM pmsi.t_divers
  	WHERE code = 'PURGE_IMPORT'
  	;
  
  	ANALYSE w_periode
  	;
  
  	
  	DELETE FROM pmsi.p_imports 
  	USING w_periode
  	WHERE etat = 'G' AND
  		(
  		date_fin = '20991231' OR 
  		date_fin <= date_purge
  		) AND
  		oid NOT IN (SELECT import_id FROM pmsi.p_rss GROUP BY 1 HAVING count(*) >= 10) AND date_import < date(date_trunc('year',now())-interval '1 year')
  	;
  
  	
  	DELETE FROM pmsi.p_imports 
  	USING w_periode
  	WHERE etat = 'G' AND
  		(
  		date_fin = '20991231' OR 
  		date_fin <= date_purge
  		) AND
  		oid NOT IN (SELECT import_id FROM pmsi.p_rss GROUP BY 1 )
  	;
  	
  	DELETE FROM pmsi.p_imports 
  	WHERE etat <> 'G' AND 
  		date_import < date(date_trunc('month',now())-interval '6 month')
  	;
  
  
  	DELETE FROM pmsi.p_imports_data 
  	WHERE import_id NOT IN (SELECT oid FROM pmsi.p_imports)
  	;
  	DELETE FROM pmsi.p_imports_controles 
  	WHERE import_id NOT IN (SELECT oid FROM pmsi.p_imports)
  	;
  
  	ANALYSE pmsi.p_imports_controles
  	;
  	ANALYSE pmsi.p_imports_data
  	;
  
  	RETURN 'OK';
  END;