Que sabes de GNU/Linux?

martes, 8 de diciembre de 2009

Postgresql - Recalcular edad y actualizar edad con cursor

-- Function: sgl_recacl_edad()

-- DROP FUNCTION sgl_recacl_edad();

CREATE OR REPLACE FUNCTION sgl_recacl_edad()
RETURNS integer AS
$BODY$
DECLARE s_error VARCHAR(255);
DECLARE s_log VARCHAR(255);
DECLARE i_error INTEGER;
DECLARE s_id VARCHAR(20);
DECLARE cafiliados refcursor;
DECLARE c_edad smallint;
DECLARE c_fechanac timestamp without time zone;
DECLARE fechaactual timestamp without time zone;
DECLARE c_id integer;
DECLARE edad_act smallint;
DECLARE dia_nac SMALLINT;
DECLARE dia_actual SMALLINT;
DECLARE mes_actual SMALLINT;
DECLARE mes_nac SMALLINT;
BEGIN
/*
*Funcion: Permite modificar y recalcular la edad de un cliente
*/
fechaactual := current_timestamp;

/*Transaccion para los datos de los clientes*/
--START TRANSACTION;

OPEN cafiliados
FOR SELECT fechanac,edad,id FROM t_afiliados;

FETCH cafiliados INTO c_fechanac,c_edad,c_id;
/*si se encontraron filas*/
while found loop
/*calculamos la edad del cliente de nuevo*/
SELECT s_calcula_edad(c_fechanac) INTO edad_act;
dia_nac := EXTRACT(DAY FROM c_fechanac);
dia_actual := EXTRACT(DAY FROM fechaactual);
mes_nac := EXTRACT(MONTH FROM c_fechanac);
mes_actual := EXTRACT(MONTH FROM fechaactual);

IF (dia_nac = dia_actual ) AND (mes_nac = mes_actual) THEN
UPDATE t_afiliados
SET edad=edad_act
WHERE id = c_id;
/*Determinamos si se recuperaron datos desde la busqueda de info*/

IF FOUND THEN
i_error := 0;
ELSE
i_error := -1;/*no se actualizaron filas*/
END IF;
END IF;

/*sacamos los datos de la proxima fila*/
FETCH cafiliados INTO c_fechanac,c_edad,c_id;
end loop;

CLOSE cafiliados;


RETURN i_error;
END
$BODY$
LANGUAGE 'plpgsql' VOLATILE
COST 100;
ALTER FUNCTION sgl_recacl_edad() OWNER TO <>;
/*tambien se puede utilizar de la seguiente forma l actualizacion*/
UPDATE t_afiliados
SET edad=s_calcula_edad(current_timestamp,fechanac)

No hay comentarios:

Publicar un comentario