Pages

Saturday, June 1, 2013

How to store TIME only in a table?

Execute the following Microsoft SQL Server 2008 T-SQL script in Management Studio Query Editor to demonstrate storing only the time part of datetime data.

-- Demonstrate TIME (only) usage in SQL Server 2008 and onward
USE tempdb;
CREATE TABLE TimeOnly2008 (ID INT IDENTITY(1,1) PRIMARY KEY,
ModifiedDate date default (CURRENT_TIMESTAMP),
ModifiedTime time default (CURRENT_TIMESTAMP),
ModifiedDatetime datetime default (CURRENT_TIMESTAMP));

INSERT TimeOnly2008 DEFAULT VALUES;
WAITFOR DELAY '00:00:05';
INSERT TimeOnly2008 DEFAULT VALUES;

SELECT *,
       CombineDateAndTime= CONVERT(datetime,ModifiedDate)+ModifiedTime
FROM TimeOnly2008;
GO
/*
ID    ModifiedDate ModifiedTime     ModifiedDatetime        CombineDateAndTime
1     2011-12-13  07:07:28.2070000  2011-12-13 07:07:28.207 2011-12-13 07:07:28.207
2     2011-12-13  07:07:33.2100000  2011-12-13 07:07:33.210 2011-12-13 07:07:33.210
*/
DROP TABLE tempdb.dbo.TimeOnly2008

------------

No comments:

Post a Comment