How to only keep the time portion of a datetime value (SQL Server)?

拈花ヽ惹草 提交于 2019-12-24 01:15:57

问题


Here's what I use to get a HH:MM string:

CONVERT(varchar(5), time_requested, 108)

I'm thinking there may be a more elegant way, even maybe more efficient (see similar question on How to remove the time portion of a datetime value (SQL Server)?).

Requirements:

  • the final result has to be easily convertible to a string (in order to be able to concatenate some field time_created with a field such as date_created).
  • the following 2 cases must be covered: HH:MM and HH:MM:SS.

回答1:


Declare @D datetime = GetDate()      -- Data Type could be Time as well

Select CONVERT(varchar(8), @D, 108)  -- for HH:MM:SS  11:27:26
Select CONVERT(varchar(5), @D, 108)  -- for HH:MM     11:27

Failed to mention, if 2012+ you could also use Format()

Declare @D DateTime = '2016-10-22 13:30:25'

Select Format(@D,'HH:mm')         -- 13:30
Select Format(@D,'hh:mm:ss tt')   -- 01:30:25 PM



回答2:


This is too long for a comment.

Your method is fine. It produces a string representation of the value.

You can also convert to a time data type:

select cast(time_requested as time)

But note that this is "format-less" -- it contains hours, minutes, seconds, and fractions of seconds. So, your method is probably the better approach.



来源:https://stackoverflow.com/questions/40193719/how-to-only-keep-the-time-portion-of-a-datetime-value-sql-server

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