0

I have a table with composite primary key based on three columns.

(Unit, Account, service)

I have another two columns: DOB (this holds date of birth) & Age (this is a new int column which needs to be updated based on DOB and the result will be integer value of years)

I know how to retrieve the reslt for Age

select datediff(Year,DOB,GETDATE()) as AGE

But not sure how to update entire table based on the rows DOB data.

Columns are Unit, Account, Service, DOB, Age

Kermit
  • 33,827
  • 13
  • 85
  • 121
Asghar
  • 51
  • 2
  • 9

3 Answers3

2

As per the comments, it isn't wise to persist Age as it varies daily (and possibly more frequently, if you have users in different timezones).

Also, your Age vs DOB algorithm isn't accurate - see here for a better one

As a consequence, IMO this is one scenario where a non-persisted COMPUTED column makes sense, like so:

ALTER TABLE Person add Age 
AS DateDiff(yy,DOB,CURRENT_TIMESTAMP) 
- CASE WHEN DATEPART  (mm,DOB) <= DATEPART(mm,CURRENT_TIMESTAMP) 
       and DATEPART(dd, DOB) <= DATEPART(dd,CURRENT_TIMESTAMP)
    THEN 0 
    ELSE 1
  END
Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • I am running an SSIS package and boss has given me the task to enter the age based on the day package has run. The age column will be valid at the time of the transaction and that is what they are looking for. – Asghar Oct 26 '12 at 14:37
1

Get rid of the age column and calculate the age like so:

SELECT DATEDIFF(yy, DOB, getdate()) AS age FROM daffyduck

There are very rare cases that you need to store items such as age. Since age changes daily, you will have to update your records often. It is instead better to store a fixed value, such as the date of birth that can be calculated. Most DBMS's provide the functionality for doing the date arithmetic for this reason.

Kermit
  • 33,827
  • 13
  • 85
  • 121
1

To answer your question:

UPDATE dob.MyTable SET Age = datediff(Year,DOB,GETDATE());

This will update the entire table as per your requirements.

However, I strongly recommend you look at all the other answers here. Especially the ones about the calculation error in above formula.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sebastian Meine
  • 11,260
  • 29
  • 41
  • Thank you Sebastian and everyone who replied. I am certainly checking the formula and correcting it as you and others have mentioned. Thank you for pointing this up. – Asghar Oct 26 '12 at 15:59