简体   繁体   English

为什么在存储过程和简单的select命令中执行convert(datetime,getdate(),101)会产生不同的结果?

[英]Why does convert(datetime,getdate(),101) yields different results while executed in stored procedure and a simple select command?

Don't know why but while running the command 不知道为什么,但是在运行命令时

select CONVERT(datetime, getdate(),101)

gets '2016-10-27 15:53:12.743' , which is the desired result. 得到'2016-10-27 15:53:12.743' ,这是期望的结果。

However when the same command is run in a Stored Procedure like 但是,当在存储过程中运行相同的命令时,例如

if @CodeFilter2 is not null
select @CodeFilter2=CONVERT(datetime,GETDATE(),101)

yields 'Oct 27 2016 3:55PM' . 产生'Oct 27 2016 3:55PM'

Please help me understand as to why is this happening. 请帮助我了解为什么会这样。

Thanks in advance! 提前致谢!

You're converting a datetime to a datetime ? 您要将datetime转换为datetime吗? Are you expecting that the format used in convert sticks around? 您是否希望convert使用的格式不固定? It's just ignored, since it has no meaning for the conversion you're doing. 它只是被忽略,因为它对您正在进行的转换没有意义。 If you want to convert a datetime to a varchar, you need to use something like convert(varchar(max), getDate(), 101) , which will give you the correct output 10/27/2016 - I have no idea why you'd expect either of your samples to be correct; 如果要将日期时间转换为varchar,则需要使用类似convert(varchar(max), getDate(), 101) ,它将为您提供正确的输出10/27/ 10/27/2016我不知道为什么您希望您的任何一个样本都是正确的; they simply happen to work that way because the default conversion (based on locale and other context, which is very variable) happens to be your desired result (in the first case). 它们只是碰巧以这种方式工作,因为默认转换(基于语言环境和其他上下文,这是非常可变的)恰好是您想要的结果(在第一种情况下)。

If you need to rely on specific formatting you must use explicit formatting . 如果您需要依赖特定的格式,则必须使用显式格式 Or let the application handle it instead of the DB server. 或者让应用程序代替数据库服务器来处理它。 The proper format for the ODBC cannonical form (which seems to be the one you desire) is 121. Make sure you're converting to varchar or nvarchar , not datetime . ODBC规范形式的正确格式(似乎是您想要的格式)是121。确保您要转换为varcharnvarchar ,而不是datetime

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

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