Why does using left() on getdate() change it to a different data type?

流过昼夜 提交于 2019-12-23 08:47:48

问题


Running two simple select statements:

SELECT GETDATE() 

SELECT LEFT(GETDATE(), 10)

Returns:

2015-10-30 14:19:56.697 

Oct 30 201

I was expecting LEFT() to give me 2015-10-30, but instead it does not.

Does anyone know why? Is it to do with the style of the data type GETDATE returns?

Thanks!


回答1:


GETDATE() returns a datetime value. When you do SELECT GETDATE(), then the application is getting a datetime value and figuring out how to display it. The application you are using is wisely choosing an ISO-standard format.

When you do LEFT(GETDATE(), then the database needs to do an implicit conversion from datetime to some string value. For this, it uses its internationalization settings. What you are seeing is based on these settings.

Moral of the story: avoid implicit conversions. Always be explicit about what you are doing, particularly in SQL which has rather poor diagnostic capabilities. So, use CONVERT() with the appropriate format for what you want to do.




回答2:


GETDATE() command returns a DATETIME, you want to return DATE

SELECT CONVERT(DATE,GETDATE());


来源:https://stackoverflow.com/questions/33438276/why-does-using-left-on-getdate-change-it-to-a-different-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!