sqlsql-server-2008datetimessms

Convert string to date in SQLServer


I have the following strings in a table

SEP 21 2009 and OCT 7 2009

Is there any way to convert them to a date format in SQL ? I want to check them as date.


Solution

  • You can use CONVERT() or CAST()

    Using CONVERT():

    CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
    

    Eg:

    SELECT CONVERT(DATETIME,'2014/10/15 11:27:06 PM',20)
    

    See example of CONVERT() in SQL Fiddle

    Using CAST():

    CAST ( expression AS data_type [ (length)]) 
    

    Eg:

    SELECT CAST('MAR 2 1991' as date) as DateValue
    SELECT CAST('2013-04-16' AS datetime) AS DateValue
    

    See example of CAST() in SQL Fiddle.

    Read more here.