Computed bit column that returns whether another column is null

Shimmy Weitzhandler picture Shimmy Weitzhandler · Dec 6, 2009 · Viewed 9.9k times · Source

I try to have this computed column:

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]

Answer

Mark Byers picture Mark Byers · Dec 6, 2009

This works:

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)
)