Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

GetAge()

Status
Not open for further replies.

acn242

IS-IT--Management
Nov 28, 2006
39
US
I'm trying to create a function to return a customer's age.
for some reason I'm getting "syntax error near as. line 2"
I've tried taking out "as datetime" in header, but get comma syntax error????

here is the code
/*#############################*/
ALTER function "me"."GetAge"
(@in_DOB as datetime,@now as datetime)
returns int
as
begin
DECLARE @age int
IF cast(datepart(m,@now) as int) > cast(datepart(m,@in_DOB) as int)
SET @age = cast(datediff(yyyy,@in_DOB,@now) as int)
else
IF cast(datepart(m,@now) as int) = cast(datepart(m,@in_DOB) as int)
IF datepart(d,@now) >= datepart(d,@in_DOB)
SET @age = cast(datediff(yyyy,@in_DOB,@now) as int)
ELSE
SET @age = cast(datediff(yyyy,@in_DOB,@now) as int) -1
ELSE
SET @age = cast(datediff(yyyy,@in_DOB,@now) as int) - 1
RETURN @age
end
/*####################*/
 
Here is alternate code
Code:
create function GetAge (@fromdt datetime, @todt datetime) 
returns int as
return (select
  case when datepart(dd,@todt)<datepart(dd,@fromdt) then
     (datediff(mm,@fromdt,@todt)-1)/12
  else
     (datediff(mm,@fromdt,@todt))/12
  end)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top