/*
 * st_adjcorr_dbio.pgc - 조정합이 양수인 정산건 (st_adjcorr_dbio), libstdbio.a.
 * ECPG; 상관 서브쿼리로 각 정산건의 delta 합을 구해 양수인 distinct 정산건 수를 센다.
 */
#include <string.h>
#include <userlog.h>
#include "st_adjcorr_dbio.h"

long stdb_settlements_net_positive(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_sid, h_delta, positive = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE acc2 CURSOR FOR
        SELECT DISTINCT a.settlement_id,
               (SELECT coalesce(sum(a2.delta), 0) FROM st_adjust a2 WHERE a2.settlement_id = a.settlement_id)
        FROM st_adjust a WHERE a.biz_date = :h_bizdate;
    EXEC SQL OPEN acc2;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH acc2 INTO :h_sid, :h_delta;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE acc2; return -1; }
        if (h_delta > 0) positive++;
    }
    EXEC SQL CLOSE acc2;
    return positive;
}
