create or replace PROCEDURE                  RECREATE_TABLE (
    viewName IN VARCHAR2
) AS
    v_exists NUMBER;
    sqlText CLOB;
    v_err_msg VARCHAR2(4000 CHAR) := 'Job succeded';
BEGIN

    UPDATE "AP-RARTABLEAU".TABLEAU_DASHBOARDS_DEFINITIONS 
    SET LAST_REFRESH_START = SYSDATE,
        LAST_REFRESH_END = NULL,
        LAST_REFRESH_STATUS = 'RUNNING',
		ERROR_MESSAGE = NULL		
    WHERE DASHBOARD_NAME = viewName;
    commit;

    SELECT COUNT(*)
    INTO v_exists
    FROM ALL_TABLES
    WHERE TABLE_NAME = UPPER(viewName)
        AND OWNER = 'AP-RARTABLEAU';

    SELECT SQL_TEXT
    INTO sqlText
    FROM "AP-RARTABLEAU".TABLEAU_DASHBOARDS_DEFINITIONS 
    WHERE DASHBOARD_NAME = viewName;

    -- Drop the materialized view if it exists
    IF v_exists > 0 THEN
        EXECUTE IMMEDIATE 'DROP TABLE "AP-RARTABLEAU".' || viewName;
    END IF;

    -- Create the materialized view
    EXECUTE IMMEDIATE 'CREATE TABLE  "AP-RARTABLEAU".' || viewName || ' AS ' || sqlText;
    --EXECUTE IMMEDIATE 'GRANT SELECT ON  "AP-RARTABLEAU".' || viewName || ' TO "AP-RARTABLEAU"';

    -- close info in PDBADMIN.TABLEAU_DASHBOARDS_DEFINITIONS 
    UPDATE "AP-RARTABLEAU".TABLEAU_DASHBOARDS_DEFINITIONS 
    SET LAST_REFRESH_END = SYSDATE,
        LAST_REFRESH_STATUS = 'SUCCESS'
    WHERE DASHBOARD_NAME = viewName;
    commit;
EXCEPTION
    WHEN OTHERS THEN
		v_err_msg := SQLCODE ||': '|| SQLERRM; 
        UPDATE "AP-RARTABLEAU".TABLEAU_DASHBOARDS_DEFINITIONS 
        SET LAST_REFRESH_END = SYSDATE,
            LAST_REFRESH_STATUS = 'FAILED',
			ERROR_MESSAGE = v_err_msg
        WHERE DASHBOARD_NAME = viewName;
        commit;
END;
