• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 689
  • Last Modified:

SQL Server convert varchar to date - various formats

Hi.. I have a field with various dates like this.
How can I convert them ALL to / into Date field.

Aug  1 2013 12:00AM
12/29/2013
Jan 1 2011
null




thx
0
JElster
Asked:
JElster
2 Solutions
 
Steve WalesSenior Database AdministratorCommented:
You're going to want to have a look at the CONVERT function.  It will cover most of them but you may have to tinker a little with the one with the date in the format where the month name is used.

See docs: http://msdn.microsoft.com/en-us/library/ms187928.aspx
0
 
Scott PletcherSenior DBACommented:
Just CAST it to a date, unless you have a really odd format that SQL can't handle.

If you need to, you can use ISDATE() to test the column first, to see if it will convert OK or not.

SELECT
    date_string,
    CAST(date_string AS date) AS date
FROM (
    SELECT 'Aug  1 2013 12:00AM' AS date_string UNION ALL
    SELECT '12/29/2013' UNION ALL
    SELECT 'Jan 1 2011' UNION ALL
    SELECT null
) AS test_data
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now