SQL 2000: semplice funzione per calcolare l'età in anni in base ad una certa data

CREATE FUNCTION [dbo].[fn_GetAgeInYearsOnBDay] (@birthday datetime, @d datetime) 
RETURNS int AS 
BEGIN

declare @age int

select @age = datediff(yy, @birthday, @d) -
        (case when (datepart(m, @birthday) > datepart(m, @d))OR
                   (datepart(m, @birthday) = datepart(m, @d) AND
                    datepart(d, @birthday) > datepart(d, @d))
                        then 1
                        else 0
        end)

Return(@age)
END

 

USAGE:  select dbo.fn_GetAgeInYearsOnBDay('07/16/1971', Getdate())

Technorati tags:

posted @ venerdì 22 ottobre 2004 04:54

Print

Comments on this entry:

# re: SQL 2000: semplice funzione per calcolare l'età in anni in base ad una certa data

Left by Davide Mauri at 22/10/2004 11:29
Gravatar
Sull'argomento (che davvero non è banale) c'è stato un bello scambio di opinioni su DBForum:

http://www.dbforums.com/t1008741.html

alla fine sono usciti 3 metodi per calcolare correttamente l'età, tra cui anche quello proposto da te.

# re: SQL 2000: semplice funzione per calcolare l'età in anni in base ad una certa data

Left by Andrea at 25/10/2004 14:46
Gravatar
All'intero della tua funzione utilizzi la getdate()... non penso sia possibile
Per risolvere passerei la data odierna così:
CREATE FUNCTION dbo.uf_CalcoloEta
(
@dataNascita datetime,
@oggi datetime
)

RETURNS int AS

BEGIN

declare @anniEta int

select @anniEta = datediff(yy, @dataNascita, @oggi) -
(case when (datepart(m, @dataNascita) > datepart(m, @oggi))OR
(datepart(m, @dataNascita) = datepart(m, @oggi) AND
datepart(d, @dataNascita) > datepart(d, @oggi))
then 1
else 0
end)
Return(@anniEta)
END

Ciao,
Andrea
Comments have been closed on this topic.
«aprile»
domlunmarmergiovensab
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011