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

CREATE TEMP TABLE w_dbsetup AS
    SELECT 
    	t_raac.oid as keepoid,
    	t_raac.code,
    	t_raac.texte
    FROM
    	pmsi.t_raac
    WHERE 
    	t_raac.code <> t_raac.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', 'Prise en charge RAAC'),
(2, '2', 'Pas de prise en charge RAAC')
;

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

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