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

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

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    keepoid,
    code,
    texte
)
VALUES
(2, 'ATU', 'Médicaments sous ATU'),
(1, 'SUS', 'Médicaments liste en sus'),
(3, 'THROMBO', 'Médicaments thrombolytiques'),
(0, '***', 'Non renseigné')
;

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

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