如何定义这样的计算列?

时间:2012-10-31 20:46:59

标签: sql database sql-server-2008

我在SQL Server 2008中有一个Equipment表,如下所示:

CREATE TABLE [dbo].[Equipment](
[EquipmentID] [nchar](10) NOT NULL,
[EquipmentName] [nchar](50) NOT NULL,
[ProducedDate] [date] NOT NULL,
[WarrantyPeriod] [int] NOT NULL,
[SerialNumber] [nchar](20) NOT NULL,
[BrandID] [tinyint] NOT NULL,
CONSTRAINT [PK_Equipment] PRIMARY KEY CLUSTERED 
)

我希望有一个计算列WarrantyStatus,在计算时会根据UnexpiredExpired列返回ProducedDateWarrantyPeriod

这是错的,但这就是我想要的:

ALTER TABLE [dbo].[Equipment]
ADD [WarrantyStatus] AS IIF(DATEDIFF(MONTH, [ProducedDate], GETDATE()) < [WarrantyPeriod], "Unexpired", "Expired")

1 个答案:

答案 0 :(得分:2)

尝试:

ALTER TABLE [dbo].[Equipment]
ADD [WarrantyStatus] AS 
case when DATEDIFF(MONTH, [ProducedDate], GETDATE()) < [WarrantyPeriod]
then 'Unexpired'
else 'Expired'
end