When you CREATE TABLE using CASE expression to create a computed column, you do not explicitly define the data type of this column:
CREATE TABLE OrderDetail
( OrderID INT
, ProductID INT
, Qty INT
, OrderDate DATETIME
, ShipDate DATETIME
, STATUS AS CASE
WHEN shipdate is NULL AND orderdate < DATEADD( dd, -7, GETDATE()) THEN 3
WHEN shipdate is NOT NULL THEN 2
ELSE 1
end
)
GO
How SQL Server decides the data type of this column?
For a
CASEexpression it is the branch with the highest datatype precedence. In your example all three branches are literals that are in the range that will be interpreted as integers so the type of the column will beintYou can use
sql_variant_propertyto determine what datatype a literal expression is as per my answer here. e.g.2147483648is interpreted asnumeric(10,0)rather thanbigint.In the case in the question SQL Server recognises that the resultant column will be
NOT NULLbut often for calculated expressions it is necessary to wrap the expression in anISNULLto get that effect.