Advertisement
deflorator1980

Untitled

Feb 26th, 2017
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. CREATE FUNCTION remove_empty_wbs (_rev_id bigint) RETURNS SETOF BIGINT
  2.     LANGUAGE plpgsql
  3. AS $$
  4. DECLARE
  5.     _cnt INT;
  6.     _proj_id INT;
  7.     _project_cur RECORD;
  8. BEGIN
  9.     FOR _project_cur IN SELECT proj_id FROM admuser.project WHERE rev_id = _rev_id
  10.     LOOP
  11.       _proj_id := _project_cur.proj_id;
  12.       LOOP
  13.         WITH RECURSIVE temp1 ( proj_id, WBS_id, PARENT_WBS_id, wbs_short_name, PATH, LEVEL ) AS (
  14.           SELECT    T1.proj_id
  15.             , T1.WBS_id
  16.             , T1.PARENT_WBS_id
  17.             , T1.wbs_short_name
  18.             , CAST (T1.wbs_short_name AS VARCHAR (1024)) as PATH
  19.             , 1
  20.           FROM admuser.projwbs T1 WHERE T1.proj_node_flag = 'Y' AND T1.proj_id = _proj_id AND T1.rev_id=_rev_id
  21.           UNION
  22.           SELECT    T2.proj_id
  23.             , T2.WBS_id
  24.             , T2.PARENT_WBS_id
  25.             , T2.wbs_short_name
  26.             , CAST ( temp1.PATH ||'->'|| T2.wbs_short_name AS VARCHAR(1024))
  27.             , LEVEL + 1
  28.           FROM admuser.projwbs T2 INNER JOIN temp1 ON( temp1.WBS_id = T2.PARENT_WBS_id AND T2.proj_id = _proj_id AND T2.rev_id=_rev_id)
  29.         ), temp2 AS (
  30.             SELECT temp1.*, relcnt.cnt
  31.               FROM temp1
  32.               LEFT JOIN (
  33.                 SELECT
  34.                   wbs_id,
  35.                   count(*) AS cnt
  36.                 FROM admuser.task  WHERE proj_id = _proj_id AND rev_id=_rev_id
  37.                 GROUP BY wbs_id) relcnt ON temp1.wbs_id = relcnt.wbs_id
  38.         ), temp3 AS (
  39.           DELETE FROM admuser.projwbs WHERE proj_id = _proj_id AND rev_id=_rev_id AND  wbs_id IN (
  40.            SELECT a1.wbs_id  FROM temp2 a1 LEFT JOIN temp2 a2 on a1.wbs_id=a2.parent_wbs_id
  41.             WHERE a2.wbs_id is NULL and a1.cnt is null
  42.           ) RETURNING 1
  43.         )
  44.         SELECT count(*) INTO _cnt FROM temp3;
  45.  
  46.       EXIT WHEN _cnt IS NULL OR _cnt = 0;
  47.       END LOOP;
  48.    END LOOP;
  49. END;
  50. $$
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement