DBMS date command [duplicate] - sql

This question already has answers here:
Not a valid month while inserting data in oracle
(2 answers)
Closed 1 year ago.
whenever I'm trying to insert this query I'm getting an error.
CREATE TABLE dateOfBirth(dateOfBirth date);
INSERT INTO dateOfBirth(dateOfBirth)VALUES('1967-11-17');
I'm getting this error:
ORA-01843: not a valid month

Let me try your code:
SQL> CREATE TABLE dateOfBirth(dateOfBirth date);
Table created.
SQL> INSERT INTO dateOfBirth(dateOfBirth)VALUES('1967-11-17');
INSERT INTO dateOfBirth(dateOfBirth)VALUES('1967-11-17')
*
ERROR at line 1:
ORA-01861: literal does not match format string
SQL>
Doesn't work either, but - failed with a different error.
Basically, that's what happens (I mean - you get errors) when you're trying to enter a string into a date datatype column. Although it is clear at the first glance that - if you're inserting '1967-11-17' into dateOfBirth - that someone was born on 17th of November 1967. Oracle, unfortunately, isn't that enthusiastic about it. It will try to implicitly convert string to date, but - as you can see, in both your and my case it miserably failed.
Besides, what if you tried to enter e.g. 12-07-05. What is what in this string? Is 12 year (could be), month (could be) or day (could be as well)? The same goes for 07 and 05. Simply, don't do that, don't rely on implicit conversion from anything to something else.
So, what can you do about it? Obviously, insert a valid DATE datatype value! How? For example:
use date literal which always looks like date 'yyyy-mm-dd':
SQL> insert into dateofbirth (dateofbirth) values (date '1967-11-17');
1 row created.
or, use to_date function with appropriate format mask:
SQL> insert into dateofbirth (dateofbirth) values (to_date('17.11.1967', 'dd.mm.yyyy'));
1 row created.
or, alter session and set date format so that Oracle recognizes it (as you'll see, your "initial" insert will now succeed):
SQL> alter session set nls_date_format = 'yyyy-mm-dd';
Session altered.
SQL> INSERT INTO dateOfBirth(dateOfBirth)VALUES('1967-11-17');
1 row created.
Quite a few options. Therefore, if you take control over it, there'll be no problem at all.

Your insert statement tries to squeeze a string into a date column. Oracle must use implicit conversion in order to allow this to happen, this will use the sessions NLS parameters. In your example, the implicit conversion does not work with the string you have given it.
Implicit conversion is an easy way to end up with corrupt data or errors (as you are seeing now), you should always use explicit conversion so that you can be sure the string is being converted with the correct date format no matter what the session's settings are:
CREATE TABLE dateOfBirth(dateOfBirth date);
INSERT INTO dateOfBirth(dateOfBirth)VALUES(to_date('1967-11-17','yyyy-mm-dd'));
Once the data is stored in the table as a date, it can be displayed with whatever date format you prefer:
select to_char(dateOfBirth,'dd/mm/yyyy') dateOfBirth from dateOfBirth;
Or you can leave it up to the client's session settings to decide how to display it (making it the responsibility of the client to make it correct).
select dateOfBirth from dateOfBirth;

Related

SQL - Conversion failed when converting date and/or time from character string

I have 3 tables in the database that I'm working on. Out of 3, two of the tables have columns that include dates. When I checked the information schema of the columns I found that dates have the wrong data type. If you see the picture below, the highlighted columns should be stored as DATE data type.
So, I used the following query to change their data type from varchar to DATE:
ALTER TABLE [dbo].[Customer]
ALTER COLUMN DOB DATE;
ALTER TABLE [dbo].[Transactions]
ALTER COLUMN tran_date DATE;
The error that I get is:
Conversion failed when converting date and/or time from character string.
Please let me know how I can fix this error. Thanks!
What you can do is update the value using try_convert() first and then alter the column name. Note: This will set any invalid values to NULL.
update customer
set dob = try_convert(date, dob);
alter table customer alter column dbo date;
If you want to see the bad values, then before you change the table, run:
select c.*
from customer c
where try_convert(date, dob) is null and dob is not null;
You may have other ideas on how to fix the values.
You can't change from varchar to date or time or datetime by altering the column. Why? Because SQL Server does not know if the field contains '1/1/2020' or 'My dog is cute'. You will have to rebuild the table with the proper data types and then CAST() or CONVERT() the values to a true date time.
Underneath the hood, this makes more sense. A char/varchar uses one byte per character. nchar/nvarchar uses 2 bytes per character. A datetime is a number, not a character. This means you need a routine that changes this into the correct number. If you want to get deeper, the number is the number of ticks (nanoseconds) since midnight on January 1, 0001 in the Gregorian Calendar. More info.

insert timestamp oracle

I have a table with the following format:
CREATE TABLE perflog(
REQ_TIME TIMESTAMP,
RESP_TIME TIMESTAMP,
OPERATION VARCHAR2(50),
STATUS_CODE VARCHAR2(10),
STATUS_BODY VARCHAR2(30)
);
-I want to insert a timestamp in the following format: e.g. 2020-07-27T23:33:41.427330
-I'm getting the following error:
SQL> insert into perflog(REQ_TIME) VALUES(2020-07-27T23:33:41.427330);
SP2-0552: Bind variable "33" not declared.
I don't get how to declare the timestamp in order to insert dates like the above. Sorry if it is a noob question but I'm a begginer.
Simply wrapping your value in single quotes isn't enough:
insert into perflog(REQ_TIME) VALUES('2020-07-27T23:33:41.427330');
ORA-01843: not a valid month
The actual error you get will depend on your session's NLS settings (and it's possible it would work - for you, if you set your session up in a certain way - but then not necessarily for anyone else.)
Oracle has timestamp literals which you can use instead of to_timestamp(), but unfortunately they don't allow the "T":
insert into perflog(REQ_TIME) VALUES(TIMESTAMP '2020-07-27T23:33:41.427330');
ORA-01861: literal does not match format string
and you can't remove it within the call (e.g. with replace) as that then isn't a literal; so you would have to change the "T" to a space externally:
insert into perflog(REQ_TIME) VALUES(TIMESTAMP '2020-07-27 23:33:41.427330');
If you're stuck with a string with that format then use an explicitly to_timestamp() call to convert your string to the data type you want, supplying the matching format mask, including a character-literal `"T"':
insert into perflog(REQ_TIME)
VALUES(TO_TIMESTAMP('2020-07-27T23:33:41.427330', 'YYYY-MM-DD"T"HH24:MI:SS.FF6'));
db<>fiddle
It's worth noting that timestamps (and dates) do not have a specific human-readable format when stored in the database. Oracle uses one of several internal representations, depending on the flavour of datetime you're using. Your client, IDE or application will format that as a readable string when you query the data, usually using your session NLS settings again. To get the data back as a string in a specific format you should use to_char() with the appropriate format supplied.
db<>fiddle with some examples.
Use a timestamp literal using a space character instead of a T:
insert into perflog(REQ_TIME) VALUES( TIMESTAMP '2020-07-27 23:33:41.427330');
db<>fiddle

SQL oracle beginner questions

Question1:
Do i have to use to_date while inserting date?
INSERT INTO some_table (date1, date2)
VALUES (to_date('2012-10-24','YYYY-MM-DD'), to_date('2012-10-24','YYYY-MM-DD'));
Or can just insert as string? Will everything be OK this way too? I've tried and it worked.
INSERT INTO some_table (date1, date2)
VALUES ('2012-10-24',2012-10-24');
Question2:
What happens if i won't name columns that i'm inserting into? It works, but my question is if it inserts randomly now or it takes order of columns during creation of table?
INSERT INTO some_table
VALUES ('2012-10-24',2012-10-24');
1 seems to only work with the 'YYYY-MM-DD' format:
http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements003.htm#SQLRF51049 says
You can specify a DATE value as a string literal ... to specify a DATE value as a literal, you must use the Gregorian calendar. You can specify an ANSI literal... The ANSI date literal contains no time portion, and must be specified in the format 'YYYY-MM-DD'.
However, it might work with time if you use the
Alternatively you can specify an Oracle date value... The default date format for an Oracle DATE value is specified by the initialization parameter NLS_DATE_FORMAT.
For question 2, it uses the order at definition of the table. However you have to give values for all columns in that case.
Oracle supports Standard SQL date literals (since 9i).
It's DATE followed by a string with 'yyyy-mm-dd' format
DATE '2014-05-10'
It's much shorter than TO_DATE and it's independent of any NLS settings.
Similar for timestamps:
TIMESTAMP '2014-05-10 09:52:35'
Regarding your 2nd question: It's the order of columns as defined within the CREATE TABLE.
You could even do it like this one:
ALTER SESSION SET NLS_DATE_FORMAT = 'MM:YYYY:DD';
INSERT INTO some_table (date1) VALUES ('05:2014:10');
...but doing it like this is not recommended. Use TO_DATE or DATE Literal, e.g. DATE '2014-05-10' instead. It makes your life easier.

row is not inserting due to SP2-0552 error

I was trying to insert a row in a table. The below given error occurred while inserting
I don't know for what reason it occurred
SQL> insert into priya1 values ('CB','000304105000','A023596','MSC','A',05/7/2013
5:33:57 AM);
SP2-0552: Bind variable "33" not declared.
The error occurs because your date string is not correct, it is not even a string and because in many cases it will not be recognized as a date. Don't depend on defaults for date formats that happen to be in effect, make sure that your code always works by specifying what you insert.
In this case use:
create table z (z date);
insert into z (z) values (to_date('05/7/2013 5:33:57 AM','dd/mm/yyyy hh:mi:ss am'));
1 rij is aangemaakt.
i found an another way for this problem i solved using the given below query and then i inserted rows without adding to_date
alter session set nls_date_format='yyyy/mm/dd hh:mi:ss am';
it may be case when data contains single quote also produces this error for date column. in that case replace single quote with two single quotes. then record will insert
put the date time value in single quote
insert into priya1 values ('CB','000304105000','A023596','MSC','A','05/7/2013
5:33:57 AM');

How to Insert table column values: month & day from column datetype

I'm using Oracle 11g Schema
I want to select the month and day from a date concatenate it and put it into a column.
The syntax I have here makes sense but its throwing an error of..
INSERT INTO OB_SELECT_LST12_SPG WED
VALUES (((TO_CHAR(TO_DATE('RET_DATE', MM))||( TO_CHAR(TO_DATE('RET_DATE', DD)));
"SQL Error: ORA-00907: missing right parenthesis"
Any help is greatly appreciated.
Thanks.
Some points first...
Your table name has a space in in
Your not enough columns error is caused by you having more than one column in the table
You really shouldn't be doing this at all
If ret_date is a column don't encapsulate it in quotation marks (') as you won't be able to convert the string 'ret_date' into a date.
However, assuming ret_date is a string that looks like 13-06-2012
insert into ob_select_lst12_spg_wed (my_column)
values(to_char(to_date(:ret_date,'dd-mm-yyyy'),'mmdd'));
If ret_date is a date data-type then you can remove the inner conversion.
insert into ob_select_lst12_spg_wed (my_column)
values(to_char(:ret_date,'mmdd'));
to_char and to_date both make use of datetime format models, which have a number of options.
Please don't do this though. Always store dates as dates
From your comments ret_date is a date and the column wed is a character. You're getting the error bind variable not declared because you haven't specified the variable. I'm going to assume that ret_date is in another table as it's a date, in which case lose the values key-word and insert directly from that table:
insert into ob_select_lst12_spg (wed)
select to_char(ret_date,'mmdd')
from the_other_table
This shouldn't be required though, you can always convert a date into whatever you want on exit from the database. If you don't store it as a date in the database then it's easy for errors and incorrect values to creep in. I personally would change the column wed to a date, in which case your query becomes the very simple:
insert into ob_select_list12_spg (wed)
select ret_date
from the_other_table
You can then use the correct datetime format model for your needs when selecting from the database.
Sample query to get date, month from date column:
Select ((To_Char(to_date('01-FEB-73','dd-mon-yy'), 'MM'))
||( To_Char(to_date('01-JAN-73','dd-mon-yy'), 'dd')))
from dual;
if RET_DATE is date datatype then use
insert into table_name (columname)
Select ((To_Char(RET_DATE, 'MM'))
||( To_Char(RET_DATE, 'dd')))
from dual;
You are missing extra parentheses. Number of opened ( was 8 and closed ) was 5
INSERT INTO OB_SELECT_LST12_SPG(WED)
VALUES ((TO_CHAR(TO_DATE(RET_DATE, MM)))||( TO_CHAR(TO_DATE(RET_DATE, DD))));
Update
Make sure other columns are not required (i.e. Allow NULLs)