Guest User

Untitled

a guest
Jun 22nd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. USE [Karthik]
  2. GO
  3.  
  4. /****** Object: UserDefinedFunction [dbo].[GetAge] Script Date: 6/21/2018 7:13:37 PM ******/
  5. /*** Usage => select [dbo].[GetAge]('DD-MM-YYY') ***/
  6.  
  7. SET ANSI_NULLS ON
  8. GO
  9.  
  10. SET QUOTED_IDENTIFIER ON
  11. GO
  12.  
  13. CREATE FUNCTION [dbo].[GetAge] (@dateOfBirth AS datetime)
  14. RETURNS varchar(40)
  15. BEGIN
  16. DECLARE @today datetime = GETDATE()
  17. DECLARE @days int = DAY(@dateOfBirth) - DAY(@today)
  18. DECLARE @months int = MONTH(@dateOfBirth) - MONTH(@today)
  19. DECLARE @years int = DATEDIFF(YEAR, @dateOfBirth, @today) - CASE
  20. WHEN @months > 0 OR
  21. (@months = 0 AND
  22. @days > 0) THEN 1
  23. ELSE 0
  24. END
  25. SET @dateOfBirth = DATEADD(YEAR, @years, @dateOfBirth)
  26. SET @months = DATEDIFF(MONTH, @dateOfBirth, @today) - CASE
  27. WHEN @days > 0 THEN 1
  28. ELSE 0
  29. END
  30. SET @dateOfBirth = DATEADD(MONTH, @months, @dateOfBirth)
  31. SET @days = DATEDIFF(DAY, @dateOfBirth, @today)
  32. RETURN concat(@years, ' years, ', @months, ' months, and ', @days, ' days.')
  33. END
  34.  
  35.  
  36. GO
Add Comment
Please, Sign In to add comment