CREATE OR REPLACE PROCEDURE RDS.sp_DispFactLink(
    OUT cnt INT)
    LANGUAGE plpgsql
AS
$$
BEGIN
    SELECT
        COUNT(*)
    INTO cnt
    FROM RDS.T_DISP_DIRECT_FACT
    WHERE
        DispDirect IS NULL;

    UPDATE RDS.T_DISP_DIRECT_FACT fact
    SET
        dispdirect = (SELECT
                          dd.DispDirectID
                      FROM RDS.t_disp_direct dd
                      WHERE
                           (fact.FAM = dd.FAM
                               AND fact.IM = dd.IM
                               AND fact.OT = dd.ot
                               AND fact.dr = dd.dr)
                        OR (fact.FAM = dd.fam AND fact.ot = dd.ot AND fact.dr = dd.dr)
                        OR (fact.fam = dd.fam AND fact.im = dd.im AND fact.dr = dd.dr)
                        OR (fact.im = dd.im AND fact.ot = dd.ot AND fact.dr = dd.dr))
    FROM RDS.T_DISP_DIRECT_FACT fact
    WHERE
        fact.DispDirect IS NULL;

    SELECT
        cnt - COUNT(*)
    INTO cnt
    FROM rds.t_disp_direct_fact
    WHERE
        dispdirect IS NULL;
END;
$$