我有一个数据库,其中包含两个名为DateOfBirth和Age的字段,分别用于存储用户道布和年龄。根据道布匹配服务器日期,我希望Age列每年自动递增1次。
实现这一目标的最佳途径是什么?我使用的是asp.net和sql server 2008。
发布于 2011-03-24 05:03:26
与其同时存储DateOfBirth和Age,不如在计算年龄的表上创建一个计算柱:
[Age] AS datediff(year, DateOfBirth, getdate()) 所以在yout表的创建中:
-- Create Table with computed column
CREATE TABLE [dbo].[CCtest]
(
[id] [int] not NULL,
[DateOfBirth] [datetime] NULL,
-- etc...
[Age] AS datediff(year, DateOfBirth, getdate())
)
GO 如果要持久化计算值,请添加PERSISTED关键字。
一种可能性是,如果您希望以年数和月份显示年龄:
[AgeInDays] AS datediff(day, DateOfBirth, getdate()) 然后,在表上创建一个视图,将AgeInDays格式化为若干年和几个月。
下面是另一种可能性,使用[AgeYears]的计算列
create view vwCCtestAge
AS
select
id,
dateofbirth,
cast([AgeYears] as varchar(4)) + ' years ' +
cast(datediff(month, DateOfBirth, getdate())
- case when (AgeYears > 0) then (AgeYears - 1)*12
else 0
end as varchar(4)) + ' months' as Age
from cctest2
GO你应该检查边界情况..。
https://stackoverflow.com/questions/5414965
复制相似问题