CREATE OR REPLACE FUNCTION update_patient_demographics()
  RETURNS VOID AS
$BODY$
DECLARE pat RECORD;
BEGIN
  FOR pat IN SELECT *
             FROM pam_patient
             WHERE additional_demographics_id IS NULL
  LOOP
    INSERT INTO pam_fr_additional_demographics (id, month, number_of_week_of_gestation, sms_consent, week_in_month, year_of_birth, socio_professional_group, socio_professional_occupation) VALUES (nextval('pam_fr_additional_demographics_id_seq'), null, null, false, NULL, null, null, null);
    UPDATE pam_patient SET additional_demographics_id = (select max(id) from pam_fr_additional_demographics) where id = pat.id;
  END LOOP;
  RETURN;
END
$BODY$
LANGUAGE 'plpgsql';
SELECT update_patient_demographics();
select count(id) from pam_patient where additional_demographics_id is NULL ;