简体   繁体   English

如何定义这样的计算列?

[英]How can you define a computed column like this?

I have an Equipment table in SQL Server 2008 like this: 我在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 
)

I want to have a computed column WarrantyStatus that will return either Unexpired or Expired when calculating, based on columns ProducedDate and WarrantyPeriod . 我希望有一个计算列WarrantyStatus在计算时返回UnexpiredExpired ,基于ProducedDateWarrantyPeriod列。

This is wrong, but it's what I want: 这是错的,但这就是我想要的:

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

Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM