-- 1/3 : Création de la table temporaire
DROP TABLE IF EXISTS w_dbsetup
;

CREATE TEMP TABLE w_dbsetup AS
    SELECT 
    	t_nb_interventions.oid as keepoid,
    	t_nb_interventions.code,
    	t_nb_interventions.texte
    FROM
    	pmsi.t_nb_interventions
    WHERE 
    	t_nb_interventions.code <> t_nb_interventions.texte
    ORDER BY code LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    keepoid,
    code,
    texte
)
VALUES
(0, '', 'Non renseigné'),
(1, 'A', 'Nombre d''interventions < 3  '),
(2, 'B', '3 interventions'),
(3, 'C', 'Plus de 3 interventions')
;

-- 3/3 : Màj de la table iCTI
UPDATE pmsi.t_nb_interventions
SET
	code = w_dbsetup.code,
	texte = w_dbsetup.texte
FROM w_dbsetup
WHERE 
	t_nb_interventions.oid = w_dbsetup.keepoid
	AND (1 != 1
		OR t_nb_interventions.texte IS DISTINCT FROM w_dbsetup.texte
        OR t_nb_interventions.code IS DISTINCT FROM w_dbsetup.code
		)
;

INSERT INTO pmsi.t_nb_interventions (oid,code,texte)
SELECT 
    w_dbsetup.keepoid,
    w_dbsetup.code,
    w_dbsetup.texte
FROM
    w_dbsetup
    LEFT JOIN pmsi.t_nb_interventions ON t_nb_interventions.oid = w_dbsetup.keepoid
WHERE 
    t_nb_interventions.oid IS NULL
;