All pastes #574594 Raw Edit

SamuraiDio

public sql v1 · immutable
·published 2007-06-18 17:14 UTC
rendered paste body
CREATE FUNCTION seleciona_chamadas (cd_revenda int, dt_inicio timestamp, dt_fim timestamp) RETURNS integer AS $$BEGIN    DECLARE        id_revenda ALIAS FOR $1;        data_ini ALIAS FOR $3;        data_fim ALIAS FOR $4;        dis RECORD;        rev RECORD;        cli RECORD;        chamadas INTEGER;        chamadas_aux INTEGER;            chamadas := 0;        FOR dis IN SELECT * FROM revendas WHERE cd_revenda != cd_distribuidor AND cd_distribuidor = 1 ORDER BY cd_revenda LOOP        FOR cli IN SELECT * FROM clientes WHERE cd_revenda = rev.cd_revenda ORDER BY cd_cliente LOOP            SELECT INTO chamadas_aux COUNT(*) FROM chamadas_clientes WHERE cd_pessoa = cli.cd_cliente;            chamadas := chamadas + chamadas_aux;        END LOOP;        FOR rev IN SELECT * FROM revendas WHERE cd_revenda != cd_distribuidor AND cd_distribuidor = dis.cd_revenda ORDER BY cd_revenda LOOP            SELECT INTO chamadas_aux COUNT(*) FROM chamadas_revendas WHERE cd_pessoa = rev.cd_cliente;            chamadas := chamadas + chamadas_aux;        END LOOP;                chamadas := chamadas + seleciona_chamadas (dis.cd_revenda, data_ini, data_fim);    END LOOP;        RETURN chamadas;END;$$ LANGUAGE plpgsql;