Monday, November 19, 2012

Adding time to a DateTime value obtained via a SQL SELECT query

If you're looking for a good way to add a fixed duration of time to a DateTime value obtained in a SQL SELECT query, the following example provides the Transact-SQL code that can do this:

DECLARE @DurationTillExpire INT
SET @DurationTillExpire = 1

SELECT 
   dbo.Documents.DocumentId,
   dbo.Documents.LastModifiedDateTime, 
   (SELECT DATEADD(hour, @DurationTillExpire, dbo.Documents.LastModifiedDateTime)) AS 'ExpirationDateTime'
FROM dbo.Documents

In this example, I'm obtaining values from a table called Documents and am simply adding one hour to the DateTime column called LastModifiedDateTime and placing that value in a new column called ExpirationDateTime.  Of course, you may require a different duration such as days, months, or years and can account for this by adjusting the first parameter of the DATEADD function appropriately (see http://msdn.microsoft.com/en-us/library/ms186819.aspx for more info).

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.