简体   繁体   English

如何在 Oracle 数据库中插入日期和时间?

[英]How to insert date and time in Oracle databases?

I have a column in my TRANSACTION table called TxDate and another called TxTime.我的 TRANSACTION 表中有一个名为 TxDate 的列和另一个名为 TxTime 的列。 I am having trouble understanding how the TO_DATE function works.我无法理解 TO_DATE function 的工作原理。 From the research I have done the following statement looks like it is correct.从我所做的研究来看,以下陈述看起来是正确的。 Can someone please help me out in understanding how to add a date and time in Oracle.有人可以帮助我了解如何在 Oracle 中添加日期和时间。 Cheers干杯

INSERT INTO TRANSACTION 
VALUES(
    TxNbr_Seq.nextval, 
    'X', 
    1000001, 
    123.45, 
    TO_DATE('2019/05/1', 'yyyy/mm/dd'), 
    TO_DATE('12:00', 'HR:MI'), 
    '101'
);

Don't store the date and time components in separate tables.不要将日期和时间组件存储在单独的表中。

First, Oracle does not have a time datatype: it just has the date datatype, that stores both the date and time components.首先,Oracle 没有time数据类型:它只有date数据类型,存储日期和时间组件。

Second, it is usually inefficient to proceed that way.其次,以这种方式进行通常效率低下。 Sooner or later, you end up concatenating the date and time components to be able to perform proper date comparison.迟早,您最终会连接日期和时间组件,以便能够执行正确的日期比较。 It is far simpler to store both together, and use date functions if you need to display them separately.将两者存储在一起要简单得多,如果需要单独显示它们,则使用日期函数。

So, just have a single column to store date and time, say txDate , and then:所以,只有一个列来存储日期和时间,比如txDate ,然后:

INSERT INTO TRANSACTION -- better enumerate the target columns here
VALUES(
    TxNbr_Seq.nextval, 
    'X', 
    1000001, 
    123.45, 
    TO_DATE('2019/05/01 12:00', 'yyyy/mm/dd hh24:mi'),
    '101'
);

Note that Oracle uses hh24 (or hh12 , or hh if you use AM/PM format) to specify the hours format rather than hr .请注意, Oracle 使用hh24 (或hh12 ,或hh如果您使用 AM/PM 格式)来指定小时格式而不是hr

Then if you need to display the date and time separately, you can use date formatting functions:那么如果需要分别显示日期和时间,可以使用日期格式化函数:

to_char(txDate, 'yyyy/mm/dd') txDay,
to_char(txDate, 'hh24:mi'   ) txTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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