Reputation: 43
I am importing data from excel files into SQL server database. In excel ,Date field are in the format mm-dd-yyyy. Whereas SQL database imports it as yyyy-mm-dd, swapping dates to months.For ex. in excel its 01-12-2018 but in SQL it imports as 2018-12-01. Hence the dates are incorrect.
Please let me know a way to import it correctly in SQL. I am happy to import in both ways : yyyy-mm-dd or yyyy-dd-mm. I just want it to read the date correctly form excel file.
I am using import export wizard.
Upvotes: 1
Views: 24936
Reputation: 17146
Updated answer: OP mentioned in another answer comment
I am currently using import export wizard to import data.
To solve problem in Import export wizard.
Choose Flat file source - I used a sample file (sample.csv) with this data
id, dates, text
1,08-09-2018,"sample"
2,05-09-2019,"more sample"
cdates
) with definition like [cdates] as convert(date,[ dates],110)
. As you can see I added this in my SQL as last column in definition.In the case that you don't create table but insert into existing table. Alter the table to have a calculated column over the varchar date column.
Original Answer: You should import the dates as nvarchar(10) into the table and then cast them after they have been imported.
Typically nvarchar type structure is followed for all purpose and is also called staging tables. In staging tables most of the relevant mistrusted data fields are of nvarchar(N) type allowing them to be successfully imported into SQL server.
After import, you should take data from staging tables into desired tables using properly casted/converted columns in a MERGE or UP-SERT query.
In you case you should use explicit convert like
CONVERT(date,your_staging_date_column ,110)
Upvotes: 2
Reputation: 3802
If data is set as Date in Excel, you can convert it to nvarchar, and then back to date as follows:
CONVERT(date, convert(nvarchar, [date from excel]), 110);
110 in the end means that it will convert from format mm-dd-yyyy as your data is currently formatted in Excel.
If you are reading data from Excel as pure text, then it will be enough to convert that text to date:
CONVERT(date, [date from excel], 110);
This function will convert data to correct format in your table.
Upvotes: 0