Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- CREATE TYPE CIR_TYPE AS
- (
- ID integer,
- path text,
- cycle boolean
- );
- CREATE OR REPLACE FUNCTION circular_ref() RETURNS setof CIR_TYPE AS $body$
- DECLARE
- r CIR_TYPE;
- BEGIN
- For r in WITH RECURSIVE graph(ID, path, cycle) AS (
- SELECT id AS id
- , ARRAY[parentid, id] AS path
- , (parentid = id) AS cycle
- FROM mytable
- UNION ALL
- SELECT d.id, d.parentid ||path, d.parentid = ANY(path)
- FROM graph g
- JOIN mytable d ON d.id = g.path[1]
- WHERE NOT g.cycle
- )
- SELECT DISTINCT *
- FROM graph
- Loop
- If r.cycle= TRUE then
- Return NEXT r;
- End if;
- End loop;
- END;
- $body$ LANGUAGE plpgsql;
- circular_ref
- ----------------------------
- (0,"{1,0,1}",t)
- (1,"{0,1,0}",t)
- ID | Path
- ---- ------
- 0 | 1,0,1
- 1 | 0,1,0
- SELECT * FROM circular_ref();
- SELECT circular_ref();
- SELECT id, path FROM circular_ref();
Add Comment
Please, Sign In to add comment