识别某些colmns为null或为空的行

时间:2018-03-12 07:30:43

标签: sql

我有一张表,我应该验证某些列。我想知道我们是否可以编写一个查询来提供所有这些记录,而不是单独验证每个列。

让我说我有这张桌子。

id |  x  |  y  | z  
----+-----+-----+----
  1 | null| 200 | 
  2 | 100 |     | 42
  3 |  45 | 100 | 1 
  4 |     |     | 2

我想返回表中所有行的验证消息。几列不应该被验证。让我们说我不想要' Z'待验证

查询应返回以下内容

row    |  error message
-------+---------------
1      |  Column(s) 'X' should not be null or empty
2      |  Column(s) 'Y' should not be null or empty
4      |  Column(s) 'X', 'Y' should not be null or empty

3 个答案:

答案 0 :(得分:1)

你的意思是这样的吗?

select row_number() over (order by id) as row,
       'Column(s) ' + 
        stuff(case when isnull(x,'') = '' then ', ''X''' else '' end +
              case when isnull(y,'') = '' then ', ''Y''' else '' end +
              case when isnull(z,'') = '' then ', ''Z''' else '' end,1,2,'') +
       ' should not be null or empty' as [error message]
from table_name
where isnull(x,'') = '' 
   or isnull(y,'') = '' 
   or isnull(z,'') = '' 

答案 1 :(得分:0)

您可以使用一个查询选择无效记录。

select * from table_name where x = null or y = null or z = null;

我觉得编写这个查询很奇怪,因为如果我在制作表格,我就不会在第一时间插入错误的数据。关系数据库有能力做到这一点。您可以通过在不应为null的列上放置NOT NULL约束,使得无法将空数据插入到每个列中。这是一个例子。

  create table table_name (
    id   serial primary key not null,
    x    text not null,
    y    text not null,
    z    text not null
  );

答案 2 :(得分:0)

使用CTEAPPLY运算符一起检查列NULL值并将其显示为单独的结果

with cte as
(
    select a.* from table t
    cross apply (
       values (id, 'x', x), (id, 'y',  y), (id, 'z', z)
    )a(id, names, value)
    where a.value is null
)

select id,
       columns = concat('Column(s) ', stuff(
                     (select ','+names from cte where id = c.id for xml path('')),
                       1,1,''),  ' should not be null or empty')
from cte c
group by id

注意:APPLY运算符可用于SQL Server