我尝试使用此计算列:
CREATE TABLE dbo.Item
(
ItemId int NOT NULL IDENTITY (1, 1),
SpecialItemId int NULL,
--I tried this
IsSpecialItem AS ISNULL(SpecialItemId, 0) > 0,
--I tried this
IsSpecialItem AS SpecialItemId IS NOT NULL
--Both don't work
) ON [PRIMARY]
答案 0 :(得分:16)
这有效:
CREATE TABLE dbo.Item
(
ItemId int NOT NULL IDENTITY (1, 1),
SpecialItemId int NULL,
IsSpecialItem AS
CAST(CASE ISNULL(SpecialItemId, 0) WHEN 0 THEN 0 ELSE 1 END AS bit)
)
答案 1 :(得分:14)
Mark Byer's answer会导致nvarchar
列出错,无论列是int
还是nvarchar
,以下情况都会有效:
CREATE TABLE dbo.Item
(
ItemId int NOT NULL IDENTITY (1, 1),
SpecialItemId [nvarchar](50) NULL,
CAST(CASE WHEN SpecialItemId Is NULL THEN 0 ELSE 1 END AS bit)
AS IsSpecialItem
)
答案 2 :(得分:2)
SQL Server没有任何本机真正的布尔数据类型(在某种意义上,您可以使用变量代替布尔表达式,如select * from Item where IsSpecialItem
)。您可以使用保留值(在这种情况下,您的查询将是select * from Item where IsSpecialItem = 1
)来表示它的唯一方法是使用Mark建议的内容。