⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Recursive Procedure for Finding Branch Elements in FireBird and Interbase

Occasionally, I have to work with FireBird and Interbase databases. Recently, I needed to find and select all nested elements of a tree. In my case, I had to delete all nested groups of the tree when deleting the parent group and later organize the search for all nested elements.

Deletion can be done on triggers, but searching won't work. Therefore, we use a recursive procedure for selection. (I would like to note that recursion is a variant for small and not heavily loaded databases. If the database is large and the load on the database is planned to be significant, it is better to avoid recursion. An example of how to do this will be below)

We have a table with three fields (identifier, parent identifier, and name):

CREATE TABLE TEST_TABLE (
    ID         INTEGER NOT NULL,
    ID_PARENT  INTEGER,
    NAME       VARCHAR(250)
);


For such a table, the procedure for recursive deletion of an element with all nested elements will look like this:

CREATE PROCEDURE DELETE_NODES (
    ID_NODE INTEGER)
AS
DECLARE VARIABLE ID_KID INTEGER;
begin
  /* Выбираем вложения */
  for select ID from test_table where ID_PARENT = :ID_NODE INTO :ID_KID
    do begin
        /* Запускаем процедуру для всех вложенных групп поочереди (рекурсия) */
        execute procedure delete_nodes(id_kid);
    end
    /* Удаляем группу*/
    delete from test_table where ID = :ID_NODE;

  suspend;
end

That's it, instead of deletion, we can do a selection or modify the data, anything we want.

However, the given method of selection is not very convenient in the case of very large or heavily loaded databases, as it too heavily loads the server database. In such a case, for selection, I use one trick. I add a string field PATH (path) to the table, in which I will store the full path of the element (identifiers of elements from the root to the current one through a dot), and the parent elements will always have a matching start of the string, but each element will have a unique string. After that, I make a search for all inclusions not by recursion, but by a regular selection with a parameter.

It will look something like this:

1   0   1.       Основная группа
2   1   1.2.     Вторая группа
3   1   1.3.     Третья группа
4   2   1.2.4.   Вложение второй группы
5   2   1.2.5.   Второе вложение второй группы
6   3   1.3.6.   Подгруппа для группы номер с ID=3


Thus, making a selection for group number 2 in this way:

select * from TEST_TABLE where PATH like \'1.2.%\'

We will get a selection of all descendants of this element, including itself.

That's it.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.