Tuesday, April 5, 2011

How do I convert eg '22/03/2005' to a datetime in SQL Server

Its SQL Server 2000. I am starting with a character string in the format DD/MM/YYYY

From stackoverflow
  • Here's the table: http://msdn.microsoft.com/en-us/library/ms187928.aspx

    Sample:

    select convert(datetime,'22/03/2005', 103)
    
    cindi : perfect, thanks
  • It depends your the context.
    SQL Server understands '2010-06-21' as a date without requiring any convert/cast, so I would just use the string in the format 'yyyy-mm-dd' if that suits your needs.
    Otherwise, the other responses using cast may be better if you need to compare with date fields containing hours as well.

    gbn : You'd use yyyymmdd. 2010-06-21 is *not* safe if you have say british language settings
  • SET DATEFORMAT dmy
    SELECT CAST('22/03/2005' AS datetime)
    
    or 
    
    SELECT convert(datetime,'22/03/2005', 103)
    
    cindi : didn't know that set dateformat thing - handy not to have to remember opcodes

0 comments:

Post a Comment