简体   繁体   中英

Why does my dynamic to_char not work?

I want to return a list of results with the following WHERE clause:

SELECT ... 
FROM XTABLE 
WHERE MMONTH = to_char(to_date('03/2013','mm/yyyy'),'mm')
AND MYEAR = to_char(to_date('03/2013','mm/yyyy'),'yyyy')

where MMONTH is a column of type CHAR(3 Bytes) and MYEAR is a column of type CHAR(4 Bytes).

Why doesn't it work compared to

SELECT ... 
FROM XTABLE 
WHERE TO_DATE(MMONTH,'MM') = to_date(to_char(to_date('03/2012','mm/yyyy'),'mm'),'mm')
AND TO_DATE(MYEAR,'yyyy') = to_date(to_char(to_date('03/2012','mm/yyyy'),'yyyy'),'yyyy')

I am reluctant to change the format of the date ('03/2012') on the right as I have additional queries that use the same date, so I thought using just one type of date would be good.

From the Oracle documentation,

The CHAR data type specifies a fixed-length character string. Oracle ensures that all values stored in a CHAR column have the length specified by size. If you insert a value that is shorter than the column length, then Oracle blank-pads the value to column length.

So, if you insert '03' into MMONTH column, it will have a space at the end. The output of to_char function will return simply '03' without any space. Hence, when you compare it won't match.

Recommended way, is to change the datatype of your columns to VARCHAR2. You can also change the column size of MMONTH to 2.

Following on from Ramblin' Man's explanation of the problem, if you really can't change the data type, you could use where trim(mmonth) = which has index implications, or apply rpad or or cast to your to_char . SQL Fiddle of all three options, but personally I'd go for the cast as that's most self-explanatory:

SELECT ...
FROM XTABLE 
WHERE MMONTH = cast(to_char(to_date('03/2013','mm/yyyy'),'mm') as char(3))
AND MYEAR = to_char(to_date('03/2013','mm/yyyy'),'yyyy');

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