/*
 * rc_diffhaving_dbio.pgc - 임계 초과 차이 매입 (rc_diffhaving_dbio), librcdbio.a.
 * ECPG; GROUP BY purchase_id HAVING sum(diff_amt) > 임계 커서로 큰 차이 매입 수를 센다.
 */
#include <string.h>
#include <userlog.h>
#include "rc_diffhaving_dbio.h"

long rcdb_big_diff_pids(const char *bizdate, long threshold)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_thr = threshold, h_pid, h_sum, pids = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE dhc CURSOR FOR
        SELECT purchase_id, sum(diff_amt) FROM rc_diff
        WHERE biz_date = :h_bizdate GROUP BY purchase_id HAVING sum(diff_amt) > :h_thr;
    EXEC SQL OPEN dhc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH dhc INTO :h_pid, :h_sum;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE dhc; return -1; }
        pids++;
    }
    EXEC SQL CLOSE dhc;
    return pids;
}
