Vez ou outra em psql precisamos de uma função que retorne o primeiro e o último dia do mês de uma determinada data. Isso parece simples, afinal sabemos que o inicio do mês será sempre será o dia ’01’, muito diferente do último dia do mês que pode variar conforme o mês e o ano. Na função abaixo criamos uma função que retornará o ultimo dia do mês de uma determinada data e retorne em formato do tipo timestamp. Essa função trabalhará em conjunto com a função também explicada em outro artigo chamada de GET_FIRST_DAY_OF_MONTH.
If you've ever had a need like this, the psql function below will solve your problem:
create or alter function GET_LAST_DAY_OF_MONTH (
P_DATE_REF timestamp)
returns timestamp
as
declare variable LCALC_DATE timestamp;
declare variable LCALC_NEXT_MONTH timestamp;
begin
-- Calcula o próximo mês
LCALC_NEXT_MONTH=dateadd(month, 1, :P_DATE_REF);
-- Pega o inicio do próximo mes
select cast(:LCALC_NEXT_MONTH as date) - extract(day from cast(:LCALC_NEXT_MONTH as date)) + 1
from RDB$DATABASE
into :lcalc_date;
-- agora subtrai 1 segundo
lcalc_date=dateadd(second, -1, :lcalc_date);
return :lcalc_date;
endHow to use
select GET_LAST_DAY_OF_MONTH(current_timestamp) as primeiro_dia_do_mes from RDB$DATABASE
Imagine searching for the closing period of the current month:
select * from table a where a.dt_lancamento between GET_FIRST_DAY_OF_MONTH(current_timestamp) and GET_LAST_DAY_OF_MONTH(current_timestamp)
Conclusion
Functions to retrieve the start and end of the month may seem trivial at first, but trust me, when programming with psql you will have times when you need these dates to process something important that must be counted from the beginning of the month to its end, or both. For example, consider querying entries for a monthly period, from the 1st to the end of the month, including the time suffix 23:59:59 to avoid missing transactions from the last day. The fact that the function returns a timestamp will also help you with the index, which will not require a timestamp cast to date.