CREATE OR REPLACE PROCEDURE rds.sp_prepareimportrrdirection(
    userid uuid,
    currentdatetime timestamp DEFAULT NULL
)
    LANGUAGE plpgsql
AS
$$
DECLARE
    p_userid          uuid      := userid;
    p_currentdatetime timestamp := currentdatetime;

BEGIN
    ALTER TABLE idb.rr_direction_benefits
        ADD COLUMN id uuid;
    ALTER TABLE idb.rr_direction
        ADD COLUMN id uuid;
    ALTER TABLE idb.rr_direction
        ADD COLUMN realpac int;
    ALTER TABLE idb.rr_direction
        ADD COLUMN rnumber int;
    
    DELETE
    FROM rds.t_import_rr_direction_benefits rd
        USING rds.t_import_elements ie
    WHERE ie.importelementsid = rd.importelementsid
      AND ie.users = p_userid;
    
    DELETE
    FROM rds.t_import_rr_directon rd
        USING rds.t_import_elements ie
    WHERE ie.importelementsid = rd.importelementsid
      AND ie.users = p_userid;
    
    DELETE
    FROM rds.t_import_elements
    WHERE users = p_userid
      AND type_ = (SELECT e.entityid
                   FROM vclib.t_entities e
                   WHERE e.entname = 'IMPORT_RR_DIRECTION'
                     AND e.schema = 'RDS'
                   LIMIT 1
                  );
    
    DELETE
    FROM rds.t_import_elements
    WHERE users = p_userid
      AND type_ = (SELECT e.entityid
                   FROM vclib.t_entities e
                   WHERE e.entname = 'IMPORT_RR_DIRECTION_BENEFITS'
                     AND e.schema = 'RDS'
                   LIMIT 1
                  );

END;
$$