Marking persisted computed columns NOT NULL in SQL Server Management Studio

☆樱花仙子☆ 提交于 2019-12-04 23:03:48

You may cheat this with ISNULL(Price + Taxes, 0) which uses the default value 0 for NULL computations.

As Scoregraphic notes, you can do this with ISNULL.

I often use this for computed flags, e.g., in the User table, I have a DeletedDate to know when the account was deleted. I then create a computed non-nullable boolean column called IsDeleted (type bit) like this:

isnull(case when DeletedDate is null then 0 else 1 end, 0)

The important thing to note is that the ISNULL must be on the outermost part of the expression for the designer to realize it is a non-nullable computed column.

I tried this and looking at the treeview on the left it had indeed set the column up as not null, even though in the right pane designer the checkbox was not checked...

ALTER TABLE Sales ADD Total AS ISNULL(isnull(Price,0) + isnull(Taxes,0),0) PERSISTED NOT NULL
Klaus Byskov Pedersen

According to this article nullability is determined by sqlserver based on the possible value of the computed expression. Since Price or Taxes is probably nullable, it cannot be sure that their sum is never null.

However, as @Richard suggests, using the ISNULL method avoids this. Declaring the column NOT NULL should however not be necessary as far as I have understood.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!