[英]Why does my dynamic to_char not work?
I want to return a list of results with the following WHERE clause: 我想使用以下WHERE子句返回结果列表:
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). 其中MMONTH是CHAR(3字节)类型的列,而MYEAR是CHAR(4字节)类型的列。
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. 我不愿意在右侧更改日期格式('03 / 2012'),因为我还有其他使用相同日期的查询,因此我认为只使用一种日期类型就可以了。
From the Oracle documentation, 从Oracle文档中,
The CHAR data type specifies a fixed-length character string. CHAR数据类型指定固定长度的字符串。 Oracle ensures that all values stored in a CHAR column have the length specified by size. Oracle确保存储在CHAR列中的所有值的长度均由大小指定。 If you insert a value that is shorter than the column length, then Oracle blank-pads the value to column length. 如果您插入的值短于列长度,则Oracle将值空白填充到列长度。
So, if you insert '03' into MMONTH
column, it will have a space at the end. 因此,如果在MMONTH
列中插入“ 03”,则末尾将有一个空格。 The output of to_char
function will return simply '03' without any space. to_char
函数的输出将仅返回'03',不带任何空格。 Hence, when you compare it won't match. 因此,当您比较时,它将不匹配。
Recommended way, is to change the datatype of your columns to VARCHAR2. 推荐的方法是将列的数据类型更改为VARCHAR2。 You can also change the column size of MMONTH to 2. 您还可以将MMONTH的列大小更改为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
. 从问题的Ramblin'人的解释上之后,如果你真的无法更改数据类型,你可以使用where trim(mmonth) =
具有指标意义,或申请rpad
或或cast
您to_char
。 SQL Fiddle of all three options, but personally I'd go for the cast
as that's most self-explanatory: SQL小提琴的所有三个选项,但我个人会去的cast
为最不言自明:
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.