如何将datetime转换为int数据类型 [英] how to convert datetime to int datatype

查看:1220
本文介绍了如何将datetime转换为int数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

转换为int数据类型时出现此错误



我正在使用查询转换



CAST(CONVERT(VARCHAR(8),GETDATE(),112)AS INT)



但收到此错误..?



错误:\'不允许从数据类型datetime到int的隐式转换。使用CONVERT函数运行此查询。'

I am getting this error while converting to int datatype

I am using query this to convert

CAST(CONVERT(VARCHAR(8),GETDATE(),112)AS INT)

but getting this error .. ?

Error:\'Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query.'

推荐答案

使用DATEDIFF函数如下:

Use DATEDIFF function like this:
SELECT CAST(41657 AS datetime)
SELECT DATEDIFF(DAY, 0, CAST(41657 AS datetime))


您正在将日期转换为字符串,然后尝试强制转换为int。这是没有意义的。



转换(int,getdate())



将会这样做,如果这是可能的。



你期望得到什么?您如何期望int与日期相关?你确定你不想要日,月或年功能吗?



select convert(int,getdate())每次都为我返回41658,所以它似乎忽略了时间,但是它正在工作。



足够有趣,选择CAST(CONVERT(VARCHAR(8),GETDATE(),112)AS INT)工作在SS2008。



实际上选择CONVERT(VARCHAR(8),GETDATE(),112)返回yyyymmdd,所以事实上这确实有意义,虽然我不是确定你为什么要把它作为一个int。



所以,它确实有效。您将问题标记为四个版本的SQL Server。我可以告诉你它适用于SS2008 R2。尝试只选择字符串部分,看看是否有效。
You are converting a date to a string, then trying to cast to int. That makes zero sense.

convert(int, getdate())

will do it, if it's possible.

What do you expect to get ? How do you expect the int to relate back to the date ? Are you sure you don't want the day, month or year functions ?

select convert(int, getdate()) returns 41658 for me, every time, so it seems to ignore the time, however it's working.

funny enough, select CAST(CONVERT(VARCHAR(8),GETDATE(),112)AS INT) works in SS2008.

Actually select CONVERT(VARCHAR(8),GETDATE(),112) returns yyyymmdd, so in fact that does make sense, although I'm not sure why you want it as an int.

so, it does work. You marked your question as four versions of SQL Server. I can tell you it works in SS2008 R2. Try selecting just the string part and see if that works.


这篇关于如何将datetime转换为int数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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