简体   繁体   中英

SQL Query to get the first day of the month passed in the parameer of the current year

I want to get the first day and last day of the month passed in the parameter. I tried the query-

select LAST_DAY(to_date(to_char(('01'||:P_MONTH||'2020'),'DDMMYYYY'),'YYYYMM'))
FROM DUAL

but it is erroring out.

I want to use this in a query -

select * from
GL_CODE_TAB
where effective_start_date = LAST_DAY(to_date(to_char(('01'||:P_MONTH||'2020'),'DDMMYYYY'),'YYYYMMDD'))

I want to search in the table GL_CODE_TAB as on the first/last day of the month I pass.

Eg:- If i pass "May"

select * from
GL_CODE_TAB
where effective_start_date = LAST_DAY(to_date(to_char(('01'||'May'||'2020'),'DDMMYYYY'),'YYYYMMDD'))

which should do a search like -

 select * from
    GL_CODE_TAB
    where effective_start_date = '20200531'

The inner call to TO_CHAR() is the problem. Just use TO_DATE() as follows, with the proper format specifier as second argument:

SELECT LAST_DAY(TO_DATE('01 ' || :P_MONTH || ' 2020'),'DD MONTH YYYY'))
FROM DUAL

It is unclear whether the parameter is a full or abbreviated month name (May is ambiguous in that regard). I assumed it's the former. If that's a short name, then use 'DD MON YYYY' instead.

In your query:

SELECT * 
FROM GL_CODE_TAB
WHERE effective_start_date = LAST_DAY(TO_DATE('01 ' || :P_MONTH || ' 2020'),'DD MONTH YYYY'))

Something is off in your logic. You don't need to convert strings to strings. So, I am thinking:

SELECT LAST_DAY(TO_DATE('01' || :P_MONTH || '2020', 'DDMMYYYY'))
FROM DUAL

The pattern MM is looking for a numerical month. (You also have the format pattern 'DDMMYYYY' twice in your query; I am not sure why.)

It so happens that that Oracle defaults the year to the current year and the day of the month to the current month. So, you don't even need to mess around with strings:

SELECT LAST_DAY(TO_DATE(:P_MONTH , 'MM'))
FROM DUAL;

The above assumes a numerical value for your parameter. If you want to handle a string, then:

SELECT LAST_DAY(TO_DATE('01' || :P_MONTH || '2020', 'DDMONYYYY'))
FROM DUAL

Or:

SELECT LAST_DAY(TO_DATE(:P_MONTH , 'MON'))
FROM DUAL;

If you want to pass the full month name, use MONTH instead of MON .

If you need 20200531 in the where clause, I think you want

select to_char(last_day(to_date(('01'||'May'||'2020'),'DDMMYYYY')), 'YYYYMMDD')
from dual;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM