About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Tuesday, January 10, 2012

How to store ONLY Time in SQL SERVER?

Only Time in SQL SERVER


Many a time we just need to store time part of date only, but when we look after SQL Server there is no such datatype which allow us to store only time part of the datetime.

So the question of the matter is how to store only time in sql table object. Here is a small exmple of storing time efficiently, is to use an integer column.

create table demoToStoreOnlyTime_tab(
myTotalHour smallint)

Command(s) completed successfully.

Now while inserting, you multiply the number of hours by 100, and add the minutes

insert into demoToStoreOnlyTime_tab  values( 100*datepart(hour,getdate()) + datepart(minute,getdate()))
(1 row(s) affected)

Rest let the developer do there work for formating while displaying time on front end

select CAST(LEFT(myTotalHour, LEN(myTotalHour)-2) + ':'+ RIGHT(myTotalHour, 2) AS VARCHAR(5)) as 'MyHour'  from demoToStoreOnlyTime_tab

MyHour
------
11:16

(1 row(s) affected)

Happy Coding :)

Post Reference: Vikram Aristocratic Elfin Share

1 comment: