在SQL中截断秒和毫秒 [英] Truncate seconds and milliseconds in SQL

查看:118
本文介绍了在SQL中截断秒和毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

截断数据我有点麻烦。我使用SQL的GETDATE()函数来获取当前的日期和时间并将其输入到数据库中。但是,我只想保存日期和时间直到一分钟。换句话说,我希望在输入新数据时保存dd / mm / yyyy hh:mm:00.000或dd / mm / yyyy hh:mm。我应该怎么做这个?



我应该注意我正在使用MS-SQL。

解决方案

有很多方法可以做到这一点。



例如,您可以将生成的 datetime GetDate() smalldatetime 第一,àla:

  CAST(GetDate()AS smalldatetime)

要清楚的是,这将根据当前秒数的值将生成的秒数(或向下)舍入到最接近的分钟。



编辑:



或者,您可以让SQL Server截断 datetime 为更清洁(READ:不舍入,因为值被截断)转换为 smalldatetime

  CAST(DateAdd(分钟,DateDiff(分钟,0,GetDate()),0)AS smalldatetime)
/ pre>

I'm having a bit of trouble with truncating data. I'm using SQL's GETDATE() function to get the current date and time and enter them into a database. However, I only want to save the date and time up until the minute. In other words, I want dd/mm/yyyy hh:mm:00.000 or dd/mm/yyyy hh:mm to be saved when I input new data. How can I go about doing this?

I should note I'm using MS-SQL.

解决方案

There are a number of ways to go about doing this.

For example, you could convert the generated datetime from GetDate() to a smalldatetime first, à la:

CAST(GetDate() AS smalldatetime)

To be clear, this will round the generated seconds up (or down) to the nearest minute depending up the value of the current second.

EDIT:

Alternatively, you can have SQL Server truncate a datetime for you for a "cleaner" (READ: no rounding, since the value is pre-truncated) conversion to smalldatetime:

CAST(DateAdd(minute, DateDiff(minute, 0, GetDate()), 0) AS smalldatetime)

这篇关于在SQL中截断秒和毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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