Oracle weird behavior string comparison with day of the week
While the below code prints 'Wrong Thursday',(10-FEB is a Thursday)
BEGIN
IF to_char(to_date('10-FEB-2011','DD-MON-YYYY'),'Day')='Thursday' THEN
dbms_output.put_line('Correct');
ELSE
dbms_output.put_line('Wrong '||to_char(to_date('10-FEB-2011','DD-MON-YYYY'),'Day'));
END IF;
END;
The following prints 'Correct',(09-FEB is a Wednesday)
BEGIN
IF to_char(to_date('09-FEB-2011','DD-MON-YYYY'),'Day')='Wednesday' THEN
dbms_output.put_line('Correct');
ELSE
dbms_output.put_lin开发者_Python百科e('Wrong '||to_char(to_date('09-FEB-2011','DD-MON-YYYY'),'Day'));
END IF;
END;
I've been trying to figure this out but I couldn't. Any help would be much appreciated. Thanks in advance.
to_char
by default is space-padded:
SQL> BEGIN
2 dbms_output.put_line('x' ||
3 to_char(to_date('10-FEB-2011','DD-MON-YYYY'),'Day')||
4 'x');
5 END;
6 /
xThursday x
Use the modifier fm
to prevent the padding:
SQL> BEGIN
2 IF to_char(to_date('10-FEB-2011','DD-MON-YYYY'),'fmDay')='Thursday' THEN
3 dbms_output.put_line('Correct');
4 ELSE
5 dbms_output.put_line('Wrong '||to_char(to_date('10-FEB-2011','DD-MON-YYYY'),'fmDay'));
6 END IF;
7 END;
8 /
Correct
PL/SQL procedure successfully completed
Hint:
select length(to_char(to_date('10-FEB-2011','DD-MON-YYYY'),'Day')) from dual;
returns 9, although length('Thursday')
is 8.
More information is found on Oracle's docu at http://download.oracle.com/docs/cd/E11882_01/server.112/e17118/sql_elements004.htm#i34510: The character elements MONTH, MON, DAY, and DY are padded with trailing blanks to the width of the longest full month name, the longest abbreviated month name, the longest full date name, or the longest abbreviated day name, respectively, among valid names determined by the values of NLS_DATE_LANGUAGE and NLS_CALENDAR parameters. For example, when NLS_DATE_LANGUAGE is AMERICAN and NLS_CALENDAR is GREGORIAN (the default), the largest element for MONTH is SEPTEMBER, so all values of the MONTH format element are padded to nine display characters. The values of the NLS_DATE_LANGUAGE and NLS_CALENDAR parameters are specified in the third argument to TO_CHAR and TO_* datetime functions or they are retrieved from the NLS environment of the current session.
Emphasis mine.
Another Hint: Try using a trim
All days of week will be length 9.
精彩评论