p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   SQL Server 2000 (http://p2p.wrox.com/forumdisplay.php?f=20)
-   -   Calculate age from a varchar birthdate field (http://p2p.wrox.com/showthread.php?t=39122)

nuttylife2 February 27th, 2006 09:38 PM

Calculate age from a varchar birthdate field
 
Hello there,
I have a birth date field in my database(which is a varchar field) and I need to calculate range of ages, I have tried to convert the varchar to datetime field directly in the database, but it is not letting me, then I tried various ways, one of them is below:

Select first_nm as 'First Name',last_nm as 'Last Name',
 Cast(DateDiff("mm", Convert(varchar(10),birthdt,101), Convert(varchar(10),GetDate(),101))/12 AS INTEGER) as age
I keep getting the error
"Syntax error converting datetime from character string"
Please help....!! I am going NUTS...!!

rgerald February 28th, 2006 10:37 AM

SQL Server works better when dates, including birthdates, are stored as datetime data types instead of varchar.

Once you have the birth dates stored as datetime data, the following function can be used to calculate age:

Code:

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS OFF
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_AgeCalc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_AgeCalc]
GO




CREATE FUNCTION [dbo].[f_AgeCalc] (
@DateOfBirth DateTime = NULL,
@RefDate DateTime = NULL)
RETURNS int AS 
BEGIN
RETURN (SELECT CASE
WHEN ((@DateOfBirth IS NULL) OR (@RefDate IS NULL))
THEN NULL
WHEN (@DateOfBirth > @RefDate) THEN NULL
WHEN DateADD(yyyy, DateDiff(yyyy, @DateOfBirth, @RefDate), @DateOfBirth) > @RefDate
THEN DateDiff(yyyy, @DateOfBirth, @RefDate) - 1
ELSE DateDiff(yyyy, @DateOfBirth, @RefDate)
END)
END




GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

Call the function as:

SELECT dbo.f_CalcAge(BirthDt, GetDate()) [Age]

Rand

nuttylife2 February 28th, 2006 10:04 PM

Thank you very much for your help Rand. I am very new at designing store procedures and functions. How do I convert the varchar field to a datetime field? This was designed by someone else and I tried to edit the database design to convert to datetime but I am getting an odbc error. Can't I use a convert function in this function?

Gert March 1st, 2006 04:44 AM

What is the format of your dob-string?

Gert


rgerald March 1st, 2006 11:25 AM

I just tested my function - described earlier with varchar(10) data. It works!!!

Code:

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[t_Date3]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [t_Date3]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[t_Date3]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
 BEGIN
CREATE TABLE [t_Date3] (
    [ID] [int] identity NOT NULL ,
    [Date3] varchar(10) NULL
) ON [PRIMARY]
END

GO

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('01/01/2001')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('02/29/2004')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('03/01/2004')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('03/02/2004')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('03/01/2000')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('12/31/1999')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('04/01/2003')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('02/07/1998')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('12/24/1937')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('05/08/1948')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('03/03/2003')

INSERT INTO [RandTest].[dbo].[t_Date3]([Date3])
VALUES('02/29/1960')
GO

SELECT [ID], [Date3] [Birth Date], dbo.f_AgeCalc([Date3], GetDate()) [Age] FROM [RandTest].[dbo].[t_Date3]
GO

Rand

Gert March 2nd, 2006 10:45 AM

Rand, i would think that it depends of the format he has saved his date of birth...
ymd
dmy
mdy

etc, etc..

There are a lot of different formats, and not all use the form that is normal in USA (month-day-year).

Gert


JoeFlow March 4th, 2006 01:29 PM

You need to create the following User defined function in SQL and setup a virtual field in your table called Age (or whatever):
(Just create new function, paste the following in there and save)

create function CalculateAge(@dDOB datetime, @dCurrentDate datetime) returns int as
begin
   declare @iAge int

   set @iAge = datediff(year, @dDOB, @dCurrentDate)

   -- See if birtdate is before current date.
   -- If so, subtract one from age.

   if @dCurrentDate > @dDOB
      set @iAge = @iAge - 1

   return @iAge
end

Next, add a new field to your table called age.
In the "formula" property of the field do this:
(dbo.Calculateage([birthdate],getdate()))

That's it. Use the Age field in anything without ever having to calculate anything in any code.





nuttylife2 March 6th, 2006 03:58 PM

Quote:

quote:Originally posted by Gert
 What is the format of your dob-string?

Gert



nuttylife2 March 6th, 2006 04:07 PM

Hello, Thank you very much for that tip, the idea of creating a virtual field was great. But in the formula field it is saying the formula is wrong.
My date of birth is in varchar format "08/08/1965" so I tried using your function two ways, one changing the input in the function to varchar and then converting to datetime
  set @iAge = datediff(year,Convert(varchar(20),@dDOB,101),@dCur rentDate)
then I tried coverting it in the formula field as:(dbo.Calculateage([Convert(varchar(20),birthdate,101)],getdate()))
None of them are working.
What am I doing wrong? Please help.

Quote:

quote:Originally posted by JoeFlow
 You need to create the following User defined function in SQL and setup a virtual field in your table called Age (or whatever):
(Just create new function, paste the following in there and save)

create function CalculateAge(@dDOB datetime, @dCurrentDate datetime) returns int as
begin
declare @iAge int

set @iAge = datediff(year, @dDOB, @dCurrentDate)

-- See if birtdate is before current date.
-- If so, subtract one from age.

if @dCurrentDate > @dDOB
     set @iAge = @iAge - 1

return @iAge
end

Next, add a new field to your table called age.
In the "formula" property of the field do this:
(dbo.Calculateage([birthdate],getdate()))

That's it. Use the Age field in anything without ever having to calculate anything in any code.






Gert March 7th, 2006 03:17 AM

Hi.

If you could answer my question "What is the format of the date of birth string?", then we might be able to help.
You say it is in format "08/08/1965", but that doesn't tell us mutch. What is the date-part and what is the month-part?
In your example the result will always be august 8th 1965, but how would you write august 20th 1965 in your format?
"20/08/1965" or "08/20/1965" ?

Also: what errormessages do you get from the functions?

Gert



All times are GMT -4. The time now is 05:58 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.