开发者

SQL view infers nullable column from non-null table?

I have a Product table with non-null "quantity" (decimal) and "status" (int) columns, and I created a view on this table wi开发者_Go百科th the following case expression:

SELECT P.ProductTypeId,
       (CASE WHEN P.StatusId IN (5, 8) THEN 0 ELSE -P.Quantity END) AS Quantity,
       ...
FROM Product P

ProductTypeId is correctly inferred as non-null. However, the Quantity column of this view is inferred as nullable, even though the underlying columns are not nullable. This doesn't make any sense to me.

I could use ISNULL/COALESCE to provide a default value in this case and force non-nullability, but there is no meaningful default value, and this shouldn't happen in the first place from what I understand. Any ideas what's going on?


The below explanation is for computed columns in a table. I imagine the same applies to computed columns in a view.

The Database Engine automatically determines the nullability of computed columns based on the expressions used. The result of most expressions is considered nullable even if only nonnullable columns are present, because possible underflows or overflows will produce null results as well. Use the COLUMNPROPERTY function with the AllowsNull property to investigate the nullability of any computed column in a table. An expression that is nullable can be turned into a nonnullable one by specifying ISNULL(check_expression, constant), where the constant is a nonnull value substituted for any null result.

An example where your expression could return NULL is

SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;

WITH Product(Quantity,StatusId) As
(
SELECT -2147483648,1
)
SELECT (CASE WHEN P.StatusId IN (5, 8) THEN 0 ELSE -P.Quantity END) AS Quantity  
FROM Product P
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜