Extra date from Datetime - sql

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?

Related

Can I change date format of SQL Server table permanently?

I have 2 tables in my database.
Customers_Details
Transaction
Both tables have a date column. I want to change the date format from YYYY-MM-DD to DD-MM-YYYY permanently for both tables.
Can i do it in one query or do I have to write separate query for each table?
The query which I have written is not changing the format of date permanently.
select
[customer_ID], [Gender], [Area_code],
convert(varchar, dob, 105) as DOB
from
[dbo].[customer_details]
dates are stored in an internal format. You wouldn't want to look at that string of bits anyway. But you do want to store the data that way -- to use date functions, so ordering is correct, and so on.
What you can do is add a computed column that has the string form that you want:
alter table [dbo].[customer_details] add dob_ddmmyyyy as (convert(varchar(10), dob, 105);
You can then use dob_ddmmyyyy in queries.
You can use following method, (tested in SQL 2014 and higher)
select FORMAT (GETDATE(), 'yyyy-MMM-dd')
In your case it would be as follows:
select [customer_ID],[Gender],[Area_code],
format(dob, 'dd-MM-yyyy') as DOB
from [dbo].[customer_details]

Working with dates in Teradata

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

How to convert date in mm/dd/yyyy format to yyyy-mm-dd hh:mi:ss.mmm

I'm inserting data into a table and before inserting I need to check if data exists.
I have a composite key consisted of two columns of datetime and int.
Before inserting I need to check if the data with the same time and id exists in the table.
The date that user is inserting is in 'mm/dd/yyyy'.
The datetime data in the table looks like this: '2016-01-12 00:00:00.000'.
The id field is int.
So, I have a query:
if not exists(select count(*) from table_1 where MyDate = #myDate and id = #id)
insert into table_1 .....
What is the right way to format the date user sends to match the datetime format in the table?
Check this sqlfiddle about how to use different date formats in your query. Might help you to solve it.
http://www.sqlfiddle.com/#!2/fd0b7/5
I am guessing that the question is about SQL Server, based on the syntax. The issues in the code snippet far transcend date formats.
First, the expression:
if not exists(select count(*) from table_1 where MyDate = #myDate and id = #id)
will never return true, because the subquery always returns one row with one column. If nothing matches, the column contains 0, which does exist.
You intend:
if not exists(select 1 from table_1 where MyDate = #myDate and id = #id)
Second, this check is not necessary if you wisely choose to have the database enforce the uniqueness constraint. So, define a unique index or constraint on the two columns:
create unique index unq_table_1_id_mydate on table_1(id, MyDate);
Now, the database won't let you insert duplicate values and no if is necessary.
Next, I would suggest that you fix the date format at the application layer. YYYY-MM-DD is an ISO standard date format and quite reasonable. However, if you don't want to do that, use convert():
insert into table_1(id, MyDate, .....)
select #id, convert(datetime, #MyDate, 101), . . .
The value in the database looks to be correct stored as a date/time value, so this should work fine.
You can use following line to convert date to required format in SQL server:
select FORMAT(#your_date, 'yyyy-MM-dd HH:mm:ss', 'en-US') from Your_Table

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

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!