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

CREATE TEMP TABLE w_dbsetup AS
    SELECT
        CASE WHEN oid = 0 THEN oid ELSE 1 END AS oid,
    	code,
    	texte
    FROM activite.t_type_sejour
    ORDER BY code LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    oid,
    code,
    texte
)
VALUES
(1, '0', 'Non renseigné'),
(1, '1', 'Hospitalisé'),
(1, '2', 'Ambulatoires'),
(1, '3', 'Externes'),
(1, '5', 'Séances'),
(1, '9', 'Fictifs')
;

-- 3/3 : Màj de la table iCTI
UPDATE w_dbsetup SET 
	oid =  w_dbsetup.code::bigint;

UPDATE activite.t_type_sejour SET 
	oid =  w_dbsetup.oid,
	code = w_dbsetup.code,
	texte = w_dbsetup.texte
FROM w_dbsetup
WHERE w_dbsetup.oid = t_type_sejour.oid AND w_dbsetup.oid = 0;

UPDATE activite.t_type_sejour SET
	texte = w_dbsetup.texte
FROM w_dbsetup
WHERE 1=1
	AND activite.t_type_sejour.code = w_dbsetup.code
	AND activite.t_type_sejour.texte IS DISTINCT FROM w_dbsetup.texte
;

INSERT INTO activite.t_type_sejour(oid,code,texte)
	SELECT oid, code, texte
	FROM w_dbsetup 
	WHERE 1=1 
		AND oid NOT IN (SELECT oid FROM activite.t_type_sejour)
;