-- Function: f_data_count(integer, varchar, varchar)

-- DROP FUNCTION f_data_count(integer, varchar, varchar);

CREATE OR REPLACE FUNCTION f_data_count(integer, varchar, varchar) RETURNS integer AS $$
DECLARE
    i integer;
    c integer;
    _s varchar(4000);
BEGIN
    i := 5;
    LOOP
        -- 全てのデータのみで件数チェック
        _s := 'SELECT count(basic.itemcd)
            FROM t_item_basic_attr basic
            ' || $2 || '
            INNER JOIN t_item_web_attr web ON basic.itemcd = web.itemcd
AND web.delflg = FALSE AND releasedate <= CURRENT_DATE
            WHERE basic.stock_upddate > CURRENT_DATE-' || i || ' AND basic.delflg=FALSE' || $3 || ';';

        EXECUTE _s  INTO c;

        IF $1 <= c THEN
            EXIT;
        END IF;
        IF i >= 60 THEN
            EXIT;
        END IF;
        i := i + 5;
    END LOOP;

    RETURN i;
END;

$$ LANGUAGE plpgsql;
