简体   繁体   中英

Change Date format from yyyy-mm-dd to mm/dd/yyyy Derived Column

I have a .txt flat file source. I am importing that into ssis to do some validation, manipulation to generate a .csv file.

I am in need to convert the date format which is in yyyy-mm-dd to mm/dd/yyyy for certain date column. For example: DOB column has date 1984-03-16 needs to be converted to 03/16/1984. I am using derived column transformation but not able to figure it out.

Any help is appriciated!

It wasn't clear if the original column was DATE or a string. Here is an example that demonstrates transforming the date, as requested, for both:

DECLARE @t TABLE(d DATE, s CHAR(10));

INSERT @t VALUES('1984-03-16', '1984-03-16');

SELECT d,
  CONVERT(CHAR(10), d, 101),
  CONVERT(DATE, s),
  CONVERT(CHAR(10), CONVERT(DATE, s), 101)
FROM @t;

Results:

1984-03-16          03/16/1984            1984-03-16          03/16/1984
^^^^^^^^^^ date     ^^^^^^^^^^ string     ^^^^^^^^^^ date     ^^^^^^^^^^ string

If you are storing this as a string, you really shouldn't be doing that. You lose all kinds of important things when you choose the wrong data type for things you think you need, like format. Validation is the biggest one - if you use a CHAR(10) for YYYY-MM-DD dates, what is stopping someone from entering 9999-99-99 or yeah-no-go ?

In any case, this is a formatting job that is much better handled on the other end of whatever is consuming this data. Until it is printed on a piece of paper or displayed on a report, there is absolutely no reason to take a date or datetime value and coerce it to act like a string. Even at the presentation side I question the wisdom of presenting a regional, ambiguous format like mm/dd/yyyy . Are you sure your entire audience, present and future, understands that 09/06/2013 is September 6th and not June 9th? Have any friends in England or Canada you want to run that by?

Say your Date Column is called DateCol

You will need to create three derived columns from that column and than simply concatenate them columns something like this

derivedColumns   Expression 
year             SUBSTRING(DateCol, 1, 4)
day              RIGHT(DateCol, 2)
Month            SUBSTRING(DateCol, 6, 2)

NewDate          SUBSTRING(DateCol, 6, 2) + "/" + RIGHT(DateCol, 2)+ "/"+SUBSTRING(DateCol, 1, 4)

Your NewDate Column will be in your desired format

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