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

CREATE TEMP TABLE w_dbsetup AS
    SELECT 
    	t_conversion_hp_hc.oid as keepoid,
    	t_conversion_hp_hc.code,
    	t_conversion_hp_hc.texte
    FROM
    	pmsi.t_conversion_hp_hc
    WHERE 
    	t_conversion_hp_hc.code <> t_conversion_hp_hc.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, '1', 'Conversion HC'),
(2, '2', 'Absence de conversion HC')
;

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

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