Computed bit column that returns whether another column is null
-
13-09-2019 - |
Question
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]
Solution
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)
)
OTHER TIPS
Mark Byer's answer causes an error with nvarchar
columns, the following works regardless of whether column is int
or 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
)
SQL Server doesn't have any native true boolean data type (in the sense that you could use a variable in place of a boolean expression, like select * from Item where IsSpecialItem
). The only way you can represent it is with something like Mark suggests, using reserved values (in this case, your query would be select * from Item where IsSpecialItem = 1
).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow