在SQLServer中保存日期 [英] Saving Dates in SQLServer

查看:114
本文介绍了在SQLServer中保存日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个遗留应用程序,其中输入是日期字符串,即:

I have a legacy application where the input is a date string, i.e.:


2009/06/12

06/12/2009

输入的格式始终是字符串,并且保持一致,始终为dd / mm / yyyy

The format of the input is always a string, and is consistent, it's always dd/mm/yyyy

目前,旧版应用程序仅将其插入到DateTime字段中。显然,如果服务器的本地化区域性设置发生更改,我们有一个错误

At the moment the legacy app just INSERTS this in a DateTime fields. Obviously if the Localization Culture settings of the Server change, we have a bug.

两个问题:

一个

在这种情况下,将日期存储在SQLServer中最安全的方法是什么?

是否存在可以正确解释格式,而与日期和月份的顺序无关?

二:

什么设置可以准确确定SQLServer DB的区域性,是操作系统设置,或该数据库的设置,还是什么?

欢呼

推荐答案

格式 YYYY-MM-DD 明确,这意味着SQL Server在将字符串值转换为<时不会混淆月份
和日期。 code> DATETIME 。 (我从未遇到过使用四位数年份的格式进行隐式转换的问题。)

Format YYYY-MM-DD is unambiguous, meaning that SQL Server won't confuse the month and day when converting a string value to DATETIME. (I've never experienced a problem with an implicit conversion using that format using the four digit year.)

最安全(也是最方便)的日期存储方式SQL Server中的值将使用DATETIME数据类型。

The "safest" (and most convenient) way to store date values in SQL Server is to use DATETIME datatype.

使用 CONVERT 函数显式指定输入和输出格式在 DATETIME 和字符串之间进行转换时。

Use the CONVERT function to explicitly specify the input and output formats when converting between DATETIME and strings.

基于CONVERT 样式的SQL Server 2005文档 参数值:

SQL Server 2005 Documentation on CONVERT style argument values:

http://msdn.microsoft.com/zh-CN/library/ms187928(SQL.90).aspx

要将字符串表示形式转换为DATETIME数据类型:

To convert a string representation to DATETIME datatype:

select CONVERT(datetime, '2009-06-03', 20)

第一个参数是要转换为的数据类型,第二个参数是要转换的表达式,第三个参数是样式

The first argument is datatype to convert to, the second argument is the expression to be converted, the third argument is the style.

style 20是ODBC规范格式= 'YYYY-MM-DD HH:MI :SS'(24小时制)

(style 20 is ODBC Canonical format = 'YYYY-MM-DD HH:MI:SS' (24 hour clock)

[关注度]

要转换DATETIME表达式(例如将getdate()转换为VARCHAR,格式为'YYYY-MM-DD'

To convert a DATETIME expression (e.g. getdate() to VARCHAR in 'YYYY-MM-DD' format:

select CONVERT(varchar(10), getdate(), 20)

请注意,指定varchar( 10)仅获取标题'YYYY-MM-DD HH:MM:SS'格式的前10个字符。

Note that specifying varchar(10) gets you just the first 10 characters of the etnire 'YYYY-MM-DD HH:MM:SS' format.

[/ FOLLOWUP]

[/FOLLOWUP]

关于确定默认格式的内容,这将是研究工作。通过指定格式,我们避免了默认格式引起的问题。

As to what determines the default formats, that's going to be research. We avoid the issues caused by default formats by specifying the formats.

这篇关于在SQLServer中保存日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆