我需要在 sqlserver 表中添加一个计算字段,以显示该表的其他字段是否为空或已满(全部,其中一些,无)
该字段应包含:
0=all the fields are empty(null)
1=almost one field has been filled
2=all fields contains something
实现它的最有效方法是什么?
我需要在 sqlserver 表中添加一个计算字段,以显示该表的其他字段是否为空或已满(全部,其中一些,无)
该字段应包含:
0=all the fields are empty(null)
1=almost one field has been filled
2=all fields contains something
实现它的最有效方法是什么?
可能最简单的方法是使用语句汇总所有空列case ...when
,然后将其与总列数进行比较:
CREATE TABLE [Foo] (
[Col1] int NULL,
[Col2] int NULL,
[Col3] int NULL,
[ColumnDensity] AS CASE
CASE WHEN [Col1] IS NULL THEN 0 ELSE 1 END +
CASE WHEN [Col2] IS NULL THEN 0 ELSE 1 END +
CASE WHEN [Col3] IS NULL THEN 0 ELSE 1 END
WHEN 0 /* No columns are NOT NULL */ THEN 0
WHEN 3 /* All 3 columns are NOT NULL */ THEN 2
ELSE /* Some columns are NULL and some are NOT NULL*/ 1 END
)