Impossible to store certain datetime formats in SQL Server

后端 未结 4 1476
夕颜
夕颜 2020-12-22 07:51

At the moment I have a column that holds timestamps as a datetime

The data is being stored as 10/30/2011 10:50:34 AM

My goal is to

相关标签:
4条回答
  • sql server doesn't store the data in a text format. It is stored as a number.

    Check out this page for how to format dates in sql http://msdn.microsoft.com/en-us/library/ms187928.aspx

    0 讨论(0)
  • 2020-12-22 08:34

    SQL Server doesn't store a DateTime in any string format - it's stored as an 8 byte numerical value.

    The various settings (language, date format) only influence how the DateTime is shown to you in SQL Server Management Studio - or how it is parsed when you attempt to convert a string to a DateTime.

    There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.

    The way to solve this is to use the ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.

    The ISO-8601 format is supported by SQL Server comes in two flavors:

    • YYYYMMDD for just dates (no time portion) - note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!

    or:

    • YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes.

    This is valid for SQL Server 2000 and newer.

    If you use SQL Server 2008 and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.

    Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.

    0 讨论(0)
  • 2020-12-22 08:36

    The datetime datatype tells the database engine how to store the data internally, so that you don't need to worry about human representations of the data. This is why your different UPDATE scripts don't change the format. The format is only applied when converting from the database's internal storage (a number representing the amount of time passed since a particular starting-point) and a human-readable date in the culture you require. You just need to format the date when it gets displayed, in the format suitable for your users. For example, for many, Month/Day/Year makes no sense.

    0 讨论(0)
  • 2020-12-22 08:39

    The data is stored independent of format. You only need to reformat dates for display purposes.

    0 讨论(0)
提交回复
热议问题