Cast(GetDate()as int)在正午之后出错

时间:2017-02-07 16:18:31

标签: sql sql-server-2008

这应该发生吗?或者我的查询有问题。 如果我运行以下查询

select getdate() as [Date], CAST(getdate() as date) as [Time], CAST(getdate() as INT) as INT, Cast(CAST(cast(getdate() as int) as DATETime) as Date) as finish

如果我在上午11:55:00运行[完成],则返回正确的日期 如果我在下午12:10:00运行查询[完成]返回明天日期 我试图搜索这个,如果之前已经注意到的话就找不到任何遗憾 我正在尝试按日期分组,但我也不想按时间分组,这就是我正在进行转换的原因。 运行Microsoft SQL Server 2008 R2

1 个答案:

答案 0 :(得分:1)

我认为你的问题是(如果你必须完成这些转换,我知道很久以前就需要它),你使用的是int而不是float并且正在使用转换值:

select getdate() as [Date]
    ,CAST(getdate() as date) as [Time]
    ,CAST(getdate() as INT) as INT
    ,Cast(CAST(cast(getdate() as int) as DATETime) as Date) as finishInt
    ,CAST(getdate() as float) as FLOAT
    ,Cast(CAST(cast(getdate() as float) as DATETime) as Date) as finishFloat

输出:

+-------------------------+------------+-------+------------+------------------+-------------+
|          Date           |    Time    |  INT  | finishInt  |      FLOAT       | finishFloat |
+-------------------------+------------+-------+------------+------------------+-------------+
| 2017-02-07 16:47:59.823 | 2017-02-07 | 42772 | 2017-02-08 | 42771.6999979552 | 2017-02-07  |
+-------------------------+------------+-------+------------+------------------+-------------+