获取每行为null或为空的列的计数

时间:2016-05-23 09:02:54

标签: sql sql-server

如何逐行检查所有列是空还是空?

我需要列的总计数为空或空白。请参考以下图片来帮助您。

enter image description here

结果我希望count = 4代表StudentId = 3的行,因为该行中的四列是空的。

谢谢。

5 个答案:

答案 0 :(得分:5)

您需要为每列添加CASE:

CASE WHEN col1 IS NULL THEN 1 ELSE 0 END +
CASE WHEN col2 IS NULL THEN 1 ELSE 0 END +
...

编辑:

如果你真的需要检查空字符串,你可以使用

CASE WHEN col1 <> '' THEN 0 ELSE 1 END

col1 <> ''对于NULL和空字符串都不正确。

答案 1 :(得分:2)

这可能不是最好的方法,但它确实有效。我创建了一个表变量来测试它,你应该采用你的情况中的逻辑:

DECLARE @tbl TABLE (f1 VARCHAR(10),f2 VARCHAR(10),f3 VARCHAR(10))
INSERT INTO @tbl values(NULL,NULL,'fdgfdhfgh')

SELECT *,( CASE WHEN f1 IS NULL THEN 1 ELSE 0 END + CASE WHEN f2 IS NULL then       1 ELSE 0 END + CASE WHEN f3 IS NULL THEN 1 ELSE 0 END ) Nulls FROM @tbl

答案 2 :(得分:1)

SELECT (if(col1 is null,1,0) + if(col2 is null,1,0) + if(col3 is null,1,0) + if(col4 is null,1,0) + if(col5 is null,1,0) if(col6 is null,1,0) if(col7 is null,1,0)) from yourTable

问候。

答案 3 :(得分:1)

如果不对列名进行硬编码,则此动态查询只需将表名单独传递给参数@TableName即可。

我从sys.columns表中选择列,并使用dnoeth's answer操纵逻辑。

DECLARE @TableName AS VARCHAR (256) = 'TableName';
DECLARE @SqlText AS VARCHAR(MAX) = '';

SELECT @SqlText = @SqlText + 'CASE WHEN ISNULL(' + C.[NAME] + ', '''') = '''' THEN 1 ELSE 0 END + '
    FROM SYS.OBJECTS O
    JOIN SYS.COLUMNS C ON C.OBJECT_ID = O.OBJECT_ID
    WHERE O.TYPE = 'U' AND O.[NAME] = @TableName 

SELECT @SqlText = 'SELECT ' + SUBSTRING (@SqlText, 1 , LEN(@SqlText) -1) + ' [NullsCounts], * FROM ' + @TableName

--PRINT @SqlText
EXEC (@SqlText)

答案 4 :(得分:0)

请使用以下代码。它与SQL Server 2012一起工作正常:

DECLARE @table_A TABLE 
(StudentId int IDENTITY(1,1) , FirstName Varchar(50),LastName Varchar(50),
PhoneNumber Varchar(50),Email Varchar(50),ResidencyAddress Varchar(50),
CountyId int, CityId int)

INSERT @table_A
(
    --StudentId - this column value is auto-generated
    FirstName,LastName,PhoneNumber,Email,ResidencyAddress,CountyId,CityId
)
VALUES
('John','D','6052314788','john.d@gmail.com',NULL,0, 1),
(NULL,NULL,NULL,NULL,NULL,NULL,NULL),
('Albert',NULL,'6058745962',NULL,NULL,0, 2),
('Mike','K',NULL,'mike@gmail.com',NULL,NULL, NULL)

SELECT 
    StudentId,
    CASE WHEN FirstName IS NULL THEN 1 ELSE 0 END +
    CASE WHEN LastName IS NULL THEN 1 ELSE 0 END +
    CASE WHEN PhoneNumber IS NULL THEN 1 ELSE 0 END +
    CASE WHEN Email IS NULL THEN 1 ELSE 0 END +
    CASE WHEN ResidencyAddress IS NULL THEN 1 ELSE 0 END +
    CASE WHEN CountyId IS NULL THEN 1 ELSE 0 END +
    CASE WHEN CityId IS NULL THEN 1 ELSE 0 END AS [Count of Nulls]
FROM @table_A A