Home > Enterprise >  In Oracle SQL developer how do you insert date and time
In Oracle SQL developer how do you insert date and time

Time:08-10

I am unable to insert date data and time data into an Oracle table. Please find the below query and error

INSERT INTO Sunday_Service (Service_ID, Service_date, 
                            Start_time, End_time, 
                            Service_location, No_of_children)
VALUES (Seq_service_id.nextVal, TO_DATE('YYYY-MM-DD', '2022-07-03'), 
        TO_DATE('hh24:mi:ss', '09:00:00'), TO_DATE('hh24:mi:ss', '10:15:00'), 
        'RM 2101', '10');

Error:

Error report ORA-01821

CodePudding user response:

You have your parameters switched in your TO_DATE function calls. Your TO_DATE function calls should look like this:

TO_DATE ('2022-07-03', 'YYYY-MM-DD'),
TO_DATE ('09:00:00', 'hh24:mi:ss'),
TO_DATE ('10:15:00', 'hh24:mi:ss')

CodePudding user response:

You have the arguments to to_date() the wrong way around:

INSERT INTO Sunday_Service (Service_ID, Service_date, 
                            Start_time, End_time, 
                            Service_location, No_of_children)
VALUES (Seq_service_id.nextVal,
        TO_DATE('2022-07-03', 'YYYY-MM-DD'), 
        TO_DATE('09:00:00', 'hh24:mi:ss'),
        TO_DATE('10:15:00', 'hh24:mi:ss'), 
        'RM 2101',
        '10');

But you probably want to combine the time and date, rather than holding them in separate columns; so if you removed service_date from your table you could do:

INSERT INTO Sunday_Service (Service_ID,
                            Start_time, End_time, 
                            Service_location, No_of_children)
VALUES (Seq_service_id.nextVal,
        TO_DATE('2022-07-03 09:00:00', 'YYYY-MM-DD HH24:MI:SS'), 
        TO_DATE('2022-07-03 10:15:00', 'YYYY-MM-DD HH24:MI:SS'), 
        'RM 2101',
        '10');

Apart from anything else, that will make it possible to handle service calls that span midnight or multiple days.

You could also use timestamp literals:

...
VALUES (Seq_service_id.nextVal,
        TIMESTAMP '2022-07-03 09:00:00', 
        TIMESTAMP '2022-07-03 10:15:00', 
...

or slightly more explcitly:

...
VALUES (Seq_service_id.nextVal,
        CAST(TIMESTAMP '2022-07-03 09:00:00' AS DATE), 
        CAST(TIMESTAMP '2022-07-03 10:15:00' AS DATE), 
...

If no_of_children is a number column, as it appears, then the last value should be a number - 10 rather than '10'.

  • Related