A way to store time without seconds in SQL Server

hkmswyz6  于 2023-06-21  发布在  SQL Server
关注(0)|答案(7)|浏览(154)

I want to save time in my SQL Server database in this format:

hh:mm

and not this:

hh:mm:ss

Is that possible? Is there a unique data type for that (I tried to go over the list of data types but failed to find; tried also to search on MSDN and didn't find). Is there another way? I really do not want the second to be stored.

kqhtkvqz

kqhtkvqz1#

Use Format function available from SQL Server 2012

select format(getdate(),'hh:mm')

Insert into sometable
(timepart)
values
(
format(getdate(),'hh:mm'))

Output:

07:08

a5g8bdjr

a5g8bdjr2#

No there isn't a data type for this. The smallest is time(0) , which is accurate to one second.

SELECT
    -- Returns time in the format hh:mm:ss
    CAST(GETDATE() AS TIME(0))
;

You could add a check constraint to ensure the seconds are always equal to 00, but I'm not sure what value this would add.

ajsxfq5m

ajsxfq5m3#

If you're using SQL-Server 2008+ , you can use the TIME type and just reset the seconds and just ignore them while selecting.

If not, you can consider saving them as strings(extract the HH:MI) or integers(counting minutes after 00:00). Like @destination-data said, you should note that you won't be able to use the time functions available for SQL-Server, but you will be able to convert them back to a date if necessary .

z9smfwbn

z9smfwbn4#

I think when you need only hour and minute use two columns for each one instead like this:

Hour tinyint
Minute tinyint
pes8fvy9

pes8fvy95#

Try this:

SELECT FORMAT(GETDATE(),'HH:mm')
3yhwsihp

3yhwsihp6#

It is always stored the only thing you can do is to edit the value before it gets posted so the seconds (and also the milliseconds which are also stored) are set to 0.

I do this in my c# application where all inserts end updates are passing through one routine that checks for datetime datatype and then filters out the milliseconds.

a6b3iqyw

a6b3iqyw7#

Here's an alternate suggestion if performance is important:

SELECT CONVERT([varchar](5),GETDATE(),(108))

Same result but much faster than FORMAT

If display with second is required again:

SELECT (CONVERT([varchar](5),GETDATE(),(108))+':00')

相关问题