IF OBJECT_ID('[TB]') IS NOT NULL DROP TABLE TB CREATE TABLE TB ( AGE INT, BIRTHDAY as dateadd(YY,-[AGE],Convert(nvarchar(12),getdate(),112)) ) INSERT INTO TB SELECT '24' UNION ALL SELECT '50' UNION ALL SELECT '49' select * from TB -------------------------------------------- AGE BIRTHDAY 24 1986-08-11 00:00:00.000 50 1960-08-11 00:00:00.000 49 1961-08-11 00:00:00.000 可以把新增列 弄成计算列 具体用年龄算生日不可能的,year能算出,month和day是算不出来的
age来记录年龄 感觉这个字段没必要记录 这么设计很别扭记录生日算年龄不是更好吗??
给个函数,计算年龄可以精确到天的,用法自己观察哈:---------------------------------------------------------------------- --计算年龄的函数 --算法原则:超过生日,年龄就得加1 -- --SELECT dbo.FUN_GetAge('1988-7-29', getdate()) as age ---------------------------------------------------------------------- CREATE function [dbo].[FUN_GetAge] ( @birthday datetime, --出生日期 @today datetime --截至日期 ) returns int as begin if @birthday > @today begin return 0; end
declare @age int
select @age = datediff(year, @birthday, @today)--年份差值 if datepart(month, @today) > datepart(month, @birthday)--月份超过 begin select @age = @age + 1 end if datepart(month, @today) = datepart(month, @birthday)--月份一样 begin if datepart(day, @today) >= datepart(day, @birthday)--日超过 begin select @age = @age + 1 end end return @age ; End
CREATE TABLE TB (
AGE INT,
BIRTHDAY as dateadd(YY,-[AGE],Convert(nvarchar(12),getdate(),112))
)
INSERT INTO TB
SELECT '24' UNION ALL
SELECT '50' UNION ALL
SELECT '49'
select * from TB
--------------------------------------------
AGE BIRTHDAY
24 1986-08-11 00:00:00.000
50 1960-08-11 00:00:00.000
49 1961-08-11 00:00:00.000
可以把新增列 弄成计算列
具体用年龄算生日不可能的,year能算出,month和day是算不出来的
感觉这个字段没必要记录
这么设计很别扭记录生日算年龄不是更好吗??
--计算年龄的函数
--算法原则:超过生日,年龄就得加1
--
--SELECT dbo.FUN_GetAge('1988-7-29', getdate()) as age
----------------------------------------------------------------------
CREATE function [dbo].[FUN_GetAge]
(
@birthday datetime, --出生日期
@today datetime --截至日期
)
returns int
as
begin
if @birthday > @today
begin
return 0;
end
declare @age int
select @age = datediff(year, @birthday, @today)--年份差值 if datepart(month, @today) > datepart(month, @birthday)--月份超过
begin
select @age = @age + 1
end if datepart(month, @today) = datepart(month, @birthday)--月份一样
begin
if datepart(day, @today) >= datepart(day, @birthday)--日超过
begin
select @age = @age + 1
end
end return @age ;
End