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

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

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    keepoid,
    code,
    texte
)
VALUES
(0, '0', 'Non renseigné'),
(1, '1', 'Prise en charge non programmée'),
(2, '2', 'Prise en charge programmée')
;

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

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