Add time to another datetime or combine date and time in SQL Server 2008


If you use SQL Server 2008, you can add time to a datetime directly. In SQL Server 2005 or ealier version, you need to use DateAdd function to add datepart to the new datetime. It is one of new features I like most in SQL Server 2008, but I have not played a lot with them yet.

Here is a sample table (SQL Server 2008)

–table definition

CREATE TABLE [dbo].[myDateTimes](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[myDateTime] [datetime] NULL,
	[myDateOnly] [date] NULL,
	[myTimeOnly] [time](7) NULL
) ON [PRIMARY]  

SELECT myDateTime,myDateOnly, myTimeOnly

,myDateTime + myTimeOnly AS myNewDateTimeWithTimeAdded,

CONVERT(NVARCHAR(19), CONVERT(VARCHAR(12), myDateOnly)

+

‘ ‘ + CONVERT(VARCHAR(12), myTimeOnly), 101)

AS

DateOnlyPlusTimeOnlyToNewDateTime

FROM

myDateTimes

–Or

SELECT CAST (CONVERT(NVARCHAR(19), CONVERT(VARCHAR(12), CAST(getdate() as DATE)) + ‘ ‘ + CONVERT(VARCHAR(12), CAST(getdate() as Time)), 101) AS dateTime)  AS DateOnlyPlusTimeOnlyToNewDateTime

 

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s