TSQL 从日期时间中剥离日期 [英] TSQL strip date from datetime

查看:39
本文介绍了TSQL 从日期时间中剥离日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 DATETIME 中去除 date 以便只剩下 time 进行比较的最佳方法是什么?

What is the best way to strip the date from a DATETIME so only time is left to do a comparison?

我知道我可以做到以下几点:

I know I can do the following:

CONVERT(DATETIME, CONVERT(VARCHAR(8), GETDATE(),8))

但这涉及转换和字符.如果我想检查一个时间(包括分钟)是否在 DATETIME 列中存储的其他两个时间之间,是否有一种优雅的方法可以做到这一点而不必依赖于转换为字符串?

But this involves convert and characters. If I wanted to check whether a time (including minutes) was between two other times stored in DATETIME columns, is there an elegant way to do this without having to rely on converting to character strings?

推荐答案

尝试来自 基本的 SQL Server 日期、时间和日期时间函数:

create function TimeOnly(@DateTime DateTime)
returns datetime
as
    begin
    return dateadd(day, -datediff(day, 0, @datetime), @datetime)
    end
go

或者简单地将 DateTime 转换为 SQL Server 2008 中的时间:

Or simply cast the DateTime as Time in SQL Server 2008:

declare @time as time
set @time = cast(dateTimeVal as time)

这篇关于TSQL 从日期时间中剥离日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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