Working with dates in Teradata - sql

I'm trying to insert some data into a Teradata database, this information has been originally exported from an Oracle instance, but I have a little problem with the dates, here's an example of the data:
CO_ID | CUSTOMER_NAME | JOIN_DATE
1022945 | John Carpenter | 07/03/2018 01:55:24 p.m.
And this is the create table statement:
CREATE TABLE transact (
co_id varchar(50),
user_name varchar(50),
join_date date);
Teradata is throwing error every time I execute the insert statement for example:
expected something between a string and a unicode character ...
How can I insert the information keeping the original format of the date, I have to modify the create table or there's any other trick?
thank you.

In Teradata a date is a date (without the time portion). For the insert you have to convert the input string into a valid date.
Somthing like
select cast('07/03/2018' as date format 'DD/MM/YYYY');
select cast(substr(input.join_date,1,10) as date format 'DD/MM/YYYY');
If you cast a string as date then the format clause is a description how the string parts are used to convert into a internal date format.
If you select from a date column the format clause is used to describe the wanted output format.
select cast( cast('07/03/2018' as date format 'DD/MM/YYYY') as date format 'YYYY-MM-DD')
If you add a format clause to your table definition join_date date 'DD/MM/YYYY', you define the default format for that column, which is used as the output format whenever no explicit format is given.
If you want to use the time portion too, your target column needs to be a timestamp
select cast( cast(regexp_replace('07/03/2018 01:55:24 p.m.','\.m\.', 'M')
as timestamp format 'MM/DD/YYBHH:MI:SS BT') as timestamp format 'YYYY-MM-DDBHH:MI:SS')
format phrase documentation

Related

Timestamp to date | Oracle DB

I want to select a column which is from datatype "datetime" in Orcale DB in date format.
column
1/31/2006 22:00:00 AM
I tried the following queries and got errors like below
select DATE_FORMAT(column, 'YYYY-MM-DD') as column from table
ORA-00904: "DATE_FORMAT": invalid identifier
select TO_DATE(column, 'YYYY-MM-DD') as column from table
ORA-00918: column ambiguously defined
select TO_DATE(column, 'YYYY-MM-DD') from table
org.apache.avro.SchemaParseException: Illegal character in: to_date(column,'yyyy-mm-dd')
What is the right syntax for this?
You should be using a to_char to convert a date to a specific string format.
select to_char(dat_column, 'YYYY-MM-DD') as column from table;
If you are expecting a date as return type, then that is more about the client you are using. You could set a session level parameter like this:
alter session set nls_date_format='YYYY-MM-DD';
In Oracle, there is no "datetime" data type. There is either DATE or TIMESTAMP and they both have year, month, day, hour, minute and second components (TIMESTAMP also has optional fractional seconds and time zone components). Both of those data types are binary data types and do NOT store a format.
If you want to set the time component of a DATE to midnight then use:
SELECT TRUNC(date_column) AS date_column_at_midnight
FROM table_name;
If you want to display a DATE column with only year, month and day components then you need to convert to a data type that does support a formatting; i.e. a string.
SELECT TO_CHAR(date_column, 'YYYY-MM-DD') AS formatted_date_string
FROM table_name;
To convert a column of datatype TIMESTAMP to datatype DATE use the CAST function (docs) :
select CAST(column AS DATE) as dt_column from table
The error "ORA-00918: column ambiguously defined" indicates that the SQL engine is unable to determine what table the column belongs to. To avoid that make sure to alias all joined tables and use the alias for those columns. Like this:
select CAST(t1.column AS DATE) as dt_column from table t1

Extra date from Datetime

I have a CSV file Date column with the following values:
StartDate
---------------------------
01/02/2014 0:00
09/04/2013 0:00
I want to extract only the date part from the above column value. I created the table with data type as Varchar, because if I declare it as DATETIME then I am not able to perform a bulk insert.
Date part alone you can extract using LEFT function.
(provided all your data in the format as you specified above)
select LEFT(colname,10)
You can BULK INSERT into a table where you will keep the data for intermediary storage. Try something like:
SELECT id, LEFT(CONVERT(VARCHAR, dateCol, 103), 10) FROM temptbl
Take a look at the following MSDN page for date formats available to you with CONVERT():
http://msdn.microsoft.com/en-us/library/ms187928.aspx
get the date part by splitting by "space"
cols[col_num].split(" ")[0]
and then make insert statement.
Why the table has datatype varchar?? why not date?

converting varchar to date format in sql server

I have a table with two date column. However the columns are in varchar. I need to covert them as date format.
The sample data is like this:
Account Number | Registration Date | System Status Change Date
01740567715 | 10-JUL-13 | 30-JUL-13 12.53.32.000000000 PM
I want both of these columns like this: 10-Jul-2013.
For Registration Date, I am using this code:
Update [dbo].[SysDataV2]
Set ["REGISTRATION_DATE"]= convert(datetime, (["REGISTRATION_DATE"]), 106)
But it is shwoing the result as varchar and also showing erroneous format.
For System Status Change Date I am using following code:
update [dbo].[SysData]
Set ["KYC_STATUS_CHANGED_DATE"]= REPLACE(CONVERT(datetime,convert(datetime,left(["KYC_STATUS_CHANGED_DATE"],9),103),106),' ' ,'-')
Both are changing to date format of some type (not my expected format) but in table structure they are still shown as varchar.
What am I doing wrong here?
The table's data type is still varchar. An update merely changes the string, it doesn't change the data type. What you should do is (assuming all of the dates are valid and this format is 100% consistent):
UPDATE dbo.SysData SET REGISTRATION_DATE =
CONVERT(CHAR(10), CONVERT(DATE, REGISTRATION_DATE, 106), 120);
UPDATE dbo.SysData SET KYC_STATUS_CHANGED_DATE =
CONVERT(CHAR(10), CONVERT(DATETIME, LEFT(KYC_STATUS_CHANGED_DATE, 9), 106), 120)
+ REPLACE(SUBSTRING(KYC_STATUS_CHANGED_DATE, 10, 9), '.',':')
+ RIGHT(KYC_STATUS_CHANGED_DATE, 2);
ALTER TABLE dbo.SysData ALTER COLUMN REGISTRATION_DATE DATE;
ALTER TABLE dbo.SysData ALTER COLUMN KYC_STATUS_CHANGED_DATE DATETIME;
And then stop inserting regional and potentially problematic strings. String literals representing dates / datetimes should be:
-- date only
YYYYMMDD
-- with time:
YYYY-MM-DDThh:mm:ss.nnn
But best is to simply make sure they are date or datetime values before you ever hand them off to SQL Server. Your application should be able to do this without ever converting to some arbitrary string format. Never, ever, ever store date or datetime values as strings in SQL Server. You gain nothing and you lose quite a lot.
You need to change the data type of the column from a varchar to store it as a Date. Then when you select it you can format it any way that you like. One way to do this would be to create a new column of the correct datatype and convert the data, then remove the old column. Make sure the the old column doesn't have and foreign key relationships or you will also need to transfer those over as well.
ALTER TABLE [dbo].[SysData] ADD ConvertedDate DateTime
UPDATE [dbo].[SysData] SET ConvertedDate = CAST(VarCharDate as DateTime)
ALTER TABLE [dbo].[SysData] DROP COLUMN VarCharDate

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)

inserting only date in a column in sql server

Is there a way to insert only date in a datetime column in sql server without the time?
for example
date (datetime)
===============
12-01-2000
16-02-2000
or i should store this as a varchar and cast it when retriving so that i can convert to whatever form i need.
my solution is to store it as varchar and convert it to datetime whenever needed
SELECT CONVERT(VARCHAR(10),GETDATE(),111) -- get datepart only
or
also check this post about creating date type :
create user defined data types:
create type Date from dateTime
http://weblogs.sqlteam.com/jeffs/archive/2007/10/31/sql-server-2005-date-time-only-data-types.aspx
If you are using SQLServer 2008 you can use the date data type.
The following SQL will strip out any time values and set them all to zero. So you won't need to worry whether a time value is there or not.
Select Cast(Floor(Cast(MyDateColumn as float)) as DateTime) as MyDateColumn
From dbo.MyTable
Just use smalldatetime or date. Convert your dates to your format before you update your date values or after you select date values in your app.
You can change format of date format in sql queries or in your app.
Here is a list on date formats in sql
http://www.sql-server-helper.com/tips/date-formats.aspx
Here's a link on date data types
http://databases.about.com/od/sqlserver/a/date_time.htm
Good Luck!