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

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

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    keepoid,
    code,
    texte
)
VALUES
(2, 'CH', 'Chirurgie'),
(3, 'DI', 'Dialyse'),
(4, 'GY', 'Gyneco obs'),
(1, 'ME', 'Medecine'),
(5, 'UR', 'Urgences'),
(0, '**', 'Non renseigné')
;

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

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