Posts with tag Firebird

Common table expression с рекурсией в хранимке (Firebird)

Собственно, все подробно описано в release notes, главное не забывать, что определение CTE должно быть частью основного запроса, то есть должно быть внутри конструкции for select... do... перед основным select'ом.

CREATE OR ALTER PROCEDURE TEST_TREE_WALK
RETURNS (FLD_NAME TYPE OF DOM_OBJECT_NAME)
AS
BEGIN
  FOR
/**********  declare common table expression  ****************************/
  WITH RECURSIVE group_tree AS
  (
/**************** none-recursive part, select 'root' entries *************/
    SELECT fld_id, pfld_arent_id, fld_name, CAST('' AS VARCHAR(255)) AS indent
    FROM tbl_groups WHERE fld_parent_id = -1
/*************************************************************************/
    UNION ALL
/******  recursive part  *************************************************/
    SELECT g.fld_id, g.fld_parent_id, g.fld_name, h.indent || RPAD('', 2)
    FROM tbl_groups g JOIN group_tree h ON g.fld_parent_id = h.fld_id
  )
/***** main query from declared CTE  *************************************/
  SELECT indent || fld_name
  FROM group_tree
  INTO :fld_name
  DO
  BEGIN
    SUSPEND;
  END
END