/*
 * mm_grade_having_dbio.pgc - mm 모듈 DB 접근 함수 (mm_grade_having_dbio), archived into libmmdbio.a.
 * 가맹점 수 임계 초과 등급 수 (GROUP BY ... HAVING 커서).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "mm_grade_having_dbio.h"

/* 등급별 활성 가맹점 수가 min_cnt 이상인 등급 개수. */
long mmdb_grade_having(long min_cnt)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_min = min_cnt, h_cnt;
    char h_grade[8];
    EXEC SQL END DECLARE SECTION;
    long grades = 0;
    EXEC SQL DECLARE mgh CURSOR FOR
        SELECT grade, count(*) FROM mm_merchant_ext
        WHERE status = 'ACTIVE' GROUP BY grade HAVING count(*) >= :h_min
        ORDER BY grade;
    EXEC SQL OPEN mgh;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH mgh INTO :h_grade, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mgh; return -1; }
        grades++;
    }
    EXEC SQL CLOSE mgh;
    return grades;
}
