Reputation: 3869
I have below query which is taking the last date of the month when this query is running on the current month. But as i am going to use this query in stored procedure and this procedure will run may be on the 1st or 2nd or 3rd of the current month then in this case i want to take the previous last month date everytime. For example if the query runs on 2nd or 3rd february then it will return the date with 31st January which is previous month last date.
The C_DATE
column is date datatype
Select * from C_LOG
WHERE C_DATE = LAST_DAY(to_date(sysdate,'YYYYMMDD'))-1
Upvotes: 1
Views: 4211
Reputation: 143083
Yet another variation:
SELECT *
FROM c_log
WHERE c_date =
TRUNC (
LAST_DAY (
CASE
WHEN EXTRACT (DAY FROM SYSDATE) <= 3
THEN
ADD_MONTHS (SYSDATE, -1)
ELSE
SYSDATE
END));
Upvotes: 2
Reputation: 168671
You can use EXTRACT( DAY FROM SYSDATE )
to get the current day of the month. If this is below your threshold then you can get the last day of the previous month otherwise use the last day of the current month:
SELECT *
FROM C_LOG
WHERE C_DATE = CASE
WHEN EXTRACT( DAY FROM SYSDATE ) <= 3
THEN TRUNC( SYSDATE, 'MM' ) - INTERVAL '1' DAY
ELSE LAST_DAY( TRUNC( SYSDATE ) )
END
Note:
Do not use to_date(sysdate,'YYYYMMDD')
since TO_DATE( date_string, format_model )
takes a string as its first argument so Oracle will implicitly cast the date to a string; effectively doing:
TO_DATE(
TO_CHAR(
SYSDATE,
( SELECT value FROM NLS_SESSION_PARAMETERS WHERE parameter = 'NLS_DATE_FORMAT' )
),
'YYYYMMDD'
)
If the NLS_DATE_FORMAT
is not YYYYMMDD
then the query will fail. Since this is a session parameter, each user can change it at any time and your query will fail for any user who changes that parameter without ever changing sql of the query.
Instead, if you want to remove the time component of a DATE
data type, use the TRUNC
function.
Upvotes: 5
Reputation: 1157
you can use ADD_MONTHS function,
SELECT ADD_MONTHS(LAST_DAY(SYSDATE), -1) FROM DUAL;
you can also use the TRUNC function
SELECT TRUNC(SYSDATE, 'MM')-1 FROM DUAL;
Upvotes: 2