Monday, 30 October 2017

Calculating age using sql query

A very common requirement is to calculate aging. With the help of below SQL script, we will calculate the age very easily.
DECLARE @MTH INT,
       @Years INT,
       @Months INT,
       @Dates INT,
       @GETDays INT
DECLARE @STARTDATE AS DATETIME,
       @ENDDATE AS DATETIME

SET @STARTDATE =  format(cast('03/01/1988' as date),'yyyyMMdd')
SET @ENDDATE = GETDATE()
SET @Years = DATEDIFF(YY, @STARTDATE, @ENDDATE)
SET @Months = DATEDIFF(MM, @STARTDATE, @ENDDATE)
SET @MTH = CASE
              WHEN DATEPART(DD, @ENDDATE) <= DATEPART(DD, @STARTDATE)
                     THEN ABS(DATEDIFF(MM, DATEADD(YY, @Years, @STARTDATE), @ENDDATE)) - 1
              ELSE ABS(DATEDIFF(MM, DATEADD(YY, @Years, @STARTDATE), @ENDDATE))
              END
SET @GETDays = CASE
              WHEN DATEPART(DD, @ENDDATE) <= DATEPART(DD, @STARTDATE)
                     THEN (DATEPART(DD, @ENDDATE) + DAY(EOMONTH(DATEADD(MM, - 1, GETDATE())))) - DATEPART(DD, @STARTDATE)
              ELSE DATEPART(DD, @ENDDATE) - DATEPART(DD, @STARTDATE)
              END

SELECT CONVERT(VARCHAR(10), @Years) + ' YEAR(s) ' + CONVERT(VARCHAR(10), @MTH) + ' MONTH(s) ' + CONVERT(VARCHAR(10), @GETDays) + ' DAY(s)' Age


The input we need to give as MM/DD/YYYY format.
Here I am calculating my age. My Birth date is 03/01/1988. See the output.


 

13 comments:

  1. You are shared valuable information with us, It's very useful for learners. Thanks for sharing info about MSBI Online Training Hyderabad

    ReplyDelete
  2. You are rocking Bagesh.

    ReplyDelete
  3. Appreciate Your work, Very Informative Post on MSBI. I Would like to Share Something about MSBI Training. I think it will be beneficial for the Users here.

    ReplyDelete
  4. Appreciate Your work, Very Informative Post on MSBI. I Would like to Share Something about MSBI Training.I think it will be beneficial for the Users here.

    ReplyDelete
  5. I really enjoy the blog.Much thanks again. Really Great MSBI online course Bangalore

    ReplyDelete
  6. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful.MSBI Training Institutes in Bangalore

    ReplyDelete
  7. Through this post, I know that your good knowledge in playing with all the pieces was very helpful. I notify that this is the first place where I find issues I've been searching for. You have a clever yet attractive way of writing on Msbi online training
    Msbi online training Hyderabad
    Msbi online training India
    Msbi online course
    Msbi course
    Msbi training
    Msbi certification training

    ReplyDelete
  8. nice information thanks for sharing this article very useful for me ................!
    msbi course training

    ReplyDelete

If you have any doubt, please let me know.

Popular Posts