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

CREATE TEMP TABLE w_dbsetup AS
    SELECT
    CASE WHEN t_dashboard_widget.oid = 0 THEN t_dashboard_widget.oid ELSE 1 END AS oid, 
    t_chart.code as chart_code,
    t_dashboard.code as dashboard_code,
    t_dashboard_widget.deprecated
		FROM pmsi.t_dashboard_widget
		LEFT JOIN pmsi.t_chart ON t_chart.oid = chart_id
		LEFT JOIN pmsi.t_dashboard ON t_dashboard.oid = dashboard_id
		ORDER BY 1 LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    oid,
    chart_code,
    dashboard_code,
    deprecated
)
VALUES
(1, 'CTI_NBSEJ', 'CTI_CAS', 'f'),
(1, 'CTI_NBSEJCAS', 'CTI_CAS', 'f'),
(1, 'CTI_CAT2ADA', 'CTI_CAS', 'f'),
(1, 'CTI_CAT2AMOYDA', 'CTI_CAS', 'f'),
(1, 'CTI_INFO', 'CTI_CAS', 'f')
;

-- 3/3 : Màj de la table iCTI
TRUNCATE pmsi.t_dashboard_widget;

INSERT INTO pmsi.t_dashboard_widget(dashboard_id, chart_id, deprecated)
	SELECT
		t_dashboard.oid,
		t_chart.oid,
		w_dbsetup.deprecated
	FROM w_dbsetup
	LEFT JOIN pmsi.t_chart ON t_chart.code = chart_code
	LEFT JOIN pmsi.t_dashboard ON t_dashboard.code = dashboard_code
;