简体   繁体   English

日期时间到varchar转换错误

[英]Datetime to varchar conversion error

I know tons of such questions are already here on SO, but my question is slightly different than questions that already exist. 我知道很多这样的问题已经在这里,但我的问题与已经存在的问题略有不同。

Scenario: Database has ApptDt column of type DateTime, with values in format "yyyy-mm-dd hh:mm:ss". 场景:数据库具有DateTime类型的ApptDt列,其值为“yyyy-mm-dd hh:mm:ss”。 I am from India and dates are passed in European Format, "dd-mm-yyyy". 我来自印度,日期以欧洲格式传递,“dd-mm-yyyy”。 So every time I am getting this error: 所以每次我收到这个错误:

The Conversion of a Varchar Datatype to a datetime results in an out of range value 将Varchar数据类型转换为日期时间会导致超出范围值

Sample Query 1: 示例查询1:

  Declare @EffectiveDt as varchar(29)
  Set @EffectiveDt = '27/07/2013'
  print Convert(DateTime,@EffectiveDt,102) // throws above error 

Sample Query 2: 示例查询2:

Declare @EffectiveDt as varchar(29)
Set @EffectiveDt = '07/27/2013'    
print Convert(DateTime,@EffectiveDt,104) // throws above error too

Question: 题:

  1. The two formats are valid and conversions are allowed in T-Sql; 这两种格式是有效的,并且在T-Sql中允许转换; why are such errors thrown? 为什么抛出这样的错误?

  2. Are there any generic functions or scenarios to hold such to-and-from conversions inside SQL? 是否有任何通用函数或方案来保存SQL内部的这种来回转换?

What you should be doing is NOT using regional formats like d/m/y or m/d/y in the first place. 您应该做的不是首先使用d/m/ym/d/y等区域格式。 If you use an unambiguous string format like yyyymmdd then there will never be an issue and you don't have to find all kinds of crazy workarounds. 如果你使用像yyyymmdd这样明确的字符串格式,那么永远不会有问题,你不必找到各种疯狂的解决方法。 Just format your dates in a clear and standard way in the first place. 只需首先以清晰标准的方式格式化日期。

Just because you're from India does not mean you have to use regional strings to represent dates. 仅仅因为你来自印度并不意味着你必须使用区域字符串来表示日期。 If you're letting people enter dates in free text (which is the only way I could explain you ended up with 07/27/2013, 27/07/2013 and 27-07-2013), stop doing that, or validate their input. 如果你让人们在自由文本中输入日期(这是我可以解释的唯一方式,你最终会在2013年7月27日,2013年7月27日和2013年7月27日),停止这样做,或者验证他们的输入。 If someone enters 05/06/2013, how are you going to know if they mean May 6th or June 5th? 如果有人进入2013年6月6日,你怎么知道他们是在5月6日还是6月5日? SQL Server can't tell either, and there is no magic way (like there is in Access) to force it to guess, and transpose the numbers if they aren't valid. SQL Server也说不出来,并且没有任何神奇的方法(比如在Access中)强制它进行猜测,如果数字无效则转置它们。 That is actually pretty scary behavior. 这实际上是非常可怕的行为。

Change 102 to 104 (german format) 更改102104 (德语格式)

SELECT Convert(DateTime,@EffectiveDt,104)  

Demo 演示

只是CAST它而不是试图在一个非常特定的文化中CONVERT它:

SELECT CAST(@EffectiveDt AS DATETIME)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM