return: text
lang: plpgsql
src: |
  DECLARE result TEXT;
  BEGIN
  	EXECUTE 'DROP TABLE IF EXISTS w_tmp;';
  	EXECUTE '
  		CREATE TEMP TABLE w_tmp AS
  		SELECT 
  			t_durees_sejour.oid,
  			t_durees_sejour.code,
  			t_durees_sejour.texte
  		FROM base.t_durees_sejour
  		ORDER BY code;';
  	EXECUTE '
  		UPDATE 
  			pmsi.t_durees_sejour_c
  		SET 
  			code = w_tmp.code,
  			texte = w_tmp.texte
  		FROM 
  			w_tmp
  		WHERE 
  			t_durees_sejour_c.oid = w_tmp.oid
  			AND (
  					t_durees_sejour_c.code IS DISTINCT FROM w_tmp.code
  					OR t_durees_sejour_c.texte IS DISTINCT FROM w_tmp.texte
  				);';
  			
  	EXECUTE 'INSERT INTO pmsi.t_durees_sejour_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 pmsi.t_durees_sejour_c
  				)
  		ORDER BY w_tmp.code;';
  			
  	EXECUTE '
  		WITH to_delete AS (
  			SELECT 
  				oid as w_id,
  				MAX(ctid) as w_ctid
  			FROM
  				pmsi.t_durees_sejour_c
  			GROUP BY oid
  			HAVING count(*) > 1
  		)
  		DELETE FROM pmsi.t_durees_sejour_c
  		USING
  			to_delete
  		WHERE 1=1
  			AND t_durees_sejour_c.oid = to_delete.w_id
  			AND t_durees_sejour_c.ctid != to_delete.w_ctid
  		';
  	
  	RETURN 'OK';
  	
  END;