Friday, August 1, 2014

How to convert date format from one varchar format to another varchar format??


Most of the time, when we design table, we store date in form of varchar format. Suppose we have a date of Birth column in varchar format "19890121" and for reporting purpose we have to take this column and format it in "01/21/1989" format.

If we try to use convert or cast function on a varchar date column and try to convert to another format, it won't work.

DECLARE @Date varchar(10) = '19890121'


Select convert(varchar(10), @Date, 101)

--> Result look like something this.

19890121

So how do we convert this Birthday column to our required format? For this we have to first convert varchar to date and then convert back to varchar in required format.

DECLARE @Date varchar(10) = '19890121'


Select convert(varchar(10), Cast(@Date as Date), 101)

--> Result

01/21/1989




No comments:

Post a Comment