return: text
lang: plpgsql
parameters:
  p0:
    type: text
    name: i_table
src: |
  DECLARE	
  	w_table TEXT;
  	result TEXT;
  BEGIN
  	-- i_table =
  	-- Table à mettre à jour, si '*NONE', ne met à jour que les codes et libellés
  	w_table = i_table;
  	IF w_table = '' THEN
  		w_table = 'activite.p_sejours';
  	END IF;
  		-- Mise à jour nouvelle zone
  		BEGIN
  			EXECUTE '
  			UPDATE ' || w_table || ' p_sejours
  			SET type_pmsi = COALESCE(t_services_facturation.type_t2a,''0'')
  			FROM activite.t_lieux
  			JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
  			WHERE p_sejours.lieu_sortie_id = t_lieux.oid AND
  				p_sejours.type_pmsi IS DISTINCT FROM COALESCE(t_services_facturation.type_t2a,''0'')';
  
  			-- Initialisation des transferts non renseignés
  			IF w_table = 'activite.p_sejours' THEN
  				INSERT INTO activite.p_sejours_transferts(sejour_id, provenance_id, destination_id)
  				SELECT p_sejours.oid, 0::bigint AS provenance_id, 0::bigint AS destination_id
  				FROM activite.p_sejours
  				LEFT JOIN activite.p_sejours_transferts ON p_sejours.oid = p_sejours_transferts.sejour_id
  				WHERE p_sejours_transferts.sejour_id IS NULL
  				;
  				UPDATE activite.p_sejours_transferts SET
  					provenance_id = COALESCE(provenance_id,0),
  					destination_id = COALESCE(destination_id,0)
  				WHERE provenance_id IS NULL OR destination_id IS NULL
  				;
  			END IF;
  				
  			
  		EXCEPTION 
  				WHEN others THEN RAISE NOTICE 'Erreur %' ,'1'; 
  		END;
  			
  		EXECUTE '
  		ANALYSE ' || w_table;
  	
  		
  	RETURN 'OK';
  END;