首先建立一个表如下:
=======================
BirthDay datetime not null
Age 通过公式计算得出
=======================
以上是表的两个字段,通过BirthDay字段的数据自动生成Age字段
Age字段的公式如下:
(case when (datediff(year,[BirthDay],getdate()) <> 0) then (ltrim(datediff(year,[BirthDay],getdate())) + '岁') else (case when (datediff(month,[BirthDay],getdate()) <> 0) then (ltrim(datediff(month,[BirthDay],getdate())) + '月') else (case when (datediff(day,[BirthDay],getdate()) <> 0) then (ltrim(datediff(day,[BirthDay],getdate())) + '天') else '' end) end) end)
这样子产生的数据就是通过填写的日期计算的。
下面是一个简单的SQL语句:
SELECT * ,
( CASE WHEN ( DATEDIFF(year, [BirthDay], GETDATE()) <> 0 )
THEN ( LTRIM(DATEDIFF(year, [BirthDay], GETDATE())) + '岁' )
ELSE ( CASE WHEN ( DATEDIFF(month, [BirthDay], GETDATE()) <> 0 )
THEN ( LTRIM(DATEDIFF(month, [BirthDay], GETDATE()))
+ '月' )
ELSE ( CASE WHEN ( DATEDIFF(day, [BirthDay],
GETDATE()) <> 0 )
THEN ( LTRIM(DATEDIFF(day, [BirthDay],
GETDATE())) + '天' )
ELSE ''
END )
END )
END )
FROM Test
以上是进行测试的代码