简体   繁体   中英

How to get DATE column in SQL Server in mm/dd/yyyy format and export it to CSV

I have a requirement to store data in a column in SQL Server with mm/dd/yyyy format. Which in my mind I would create this column with DATE datatype and use CONVERT() to convert it in mm/dd/yyyy format

CREATE TABLE [dbo].TempDate 
(
    CompanyID nvarchar (512) NULL,
    VacDate date NULL,
    OffDate date NULL,
    Duration time NULL
)

SELECT CONVERT(varchar(10), VacDate, 10) AS "StartDate"
FROM [dbo].TempDate;

No issues, I get the date in mm/dd/yyyy format. The problem is that I need to then import this table to CSV format and the date in the table is in its standard yyyy-mm-dd and so that's what gets imported in CSV. I need the date in CSV to be in mm/dd/yyyy format. I tried to INSERT into this table with CONVERT , but the date doesn't convert. Is there a way to STORE DATE in mm/dd/yyyy column right out of the gate? Like in Oracle its possible to define the column in a certain format.

Thank you for any thoughts on this.

While I believe your focus should be on the query that is getting the data for the export, if you really need it in the database you could add a computed column that displays a string representation of the data, and use that column for the export.

Alter table TempDate
Add VacDataComputed As CONVERT(varchar(10), VacDate, 10)

Edit: As mentioned, you are using 10 for the style parameter, which will render mm-dd-yyyy . If you want it in mm/dd/yyyy format, use 101. You can see more style formats here .

Your question is a bit unclear. Do you mean the CSV file contains MM/dd/yyyy format, and you want to import that into the SQL table as datetime values? So values like 12/31/2015 , 07/15/2014 etc. are in the csv data file?

If that is the case I think you have two options.

  1. Either impport the datetime column as string values, and then add a new column with datetime datatype and convert the values using string manipulation.

  2. or, just change the CSV input file and reformat the datetime column before importing it, using Notepad++ CSV Lint plug-in or Python or something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM