If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > General > Chit Chat > Age Calculation in SQL

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #16 (permalink)  
Old 01-07-11, 18:28
Pat Phelan Pat Phelan is offline
Resident Curmudgeon
 
Join Date: Feb 2004
Location: In front of the computer
Posts: 12,605
This zombie thread keeps coming back to life! I'll throw in my contribution for SQL Server 2005 and later versions:
Code:
IF Object_Id('dbo.fDeltaYYMMDD') IS NOT NULL
   DROP FUNCTION dbo.fDeltaYYMMDD
GO
--  ptp  20110107  Compute years, months, days since a date given in YYYYMMDD form

CREATE FUNCTION dbo.fDeltaYYMMDD(
   @cDate			VARCHAR(9)
   ) RETURNS @t TABLE (
   OriginalDate		VARCHAR(9)
,  yy				INT
,  mm				INT
,  dd				INT
   ) AS BEGIN
   
   DECLARE
      @d			DATETIME
,     @i			INT

   SET @d = Convert(DATETIME, @cDate, 112) 
   SET @i = DateDiff(month, @d, GetDate())
   IF DateAdd(month, @i, @d) > GetDate()
      SET @i = @i - 1
   
   INSERT @t
      SELECT @cDate, @i / 12, @i % 12, DateDiff(day
,        DateAdd(month, @i, @d), GetDate())
   
   RETURN
END
GO
--  Quick test of dbo.fDeltaYYMMDD

SELECT *
   FROM (SELECT     '20110106' AS d
   UNION ALL SELECT '20101207'
   UNION ALL SELECT '20100107'
   UNION ALL SELECT '20100106'
   UNION ALL SELECT '20100107'
   UNION ALL SELECT '20100108'
   UNION ALL SELECT '20091207'
   UNION ALL SELECT '20091206'
      ) AS z
   CROSS APPLY dbo.fDeltaYYMMDD(d)
GO
-PatP
__________________
In theory, theory and practice are identical. In practice, theory and practice are unrelated.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On