对 SQL 条记录应用多重验证并识别所有失败的验证

Apply multiple validation to SQL records and identify all failing validations

我有一个要求,我需要在 SQL 数据库中捕获所有失败的验证。

我有以下table:

department     age 
IT             27  
IT             25  
Marketing      29
Fashion        30
IT             32
IT             28

我的验证规则如下:

  1. 部门应该是IT
  2. 年龄应该在20多岁
  3. 年龄不应该是 25 岁

这些是示例验证,我的要求是捕获所有失败的记录以及失败的条件,我通过使用 union 实现了它,如下所示:

    select department , age , 'Age is 25' as FailedValidation, 1 as FailedValidationId from 
    CENTRALFINANCETAX_IM_DEV.salluTest where age = 25
    union
    select department , age, 'Age is not in 20s' as FailedValidation, 2 as FailedValidationId from 
    CENTRALFINANCETAX_IM_DEV.salluTest where age > 29
    union
    select department , age , 'Dept not IT' as FailedValidation, 3 as FailedValidationId from 
    CENTRALFINANCETAX_IM_DEV.salluTest where department != "IT"

下面是实现的结果:

department  age FailedValidation    FailedValidationId
IT          32  Age is not in 20s   2
Marketing   29  Dept not IT         3
Fashion     30  Dept not IT         3
Fashion     30  Age is not in 20s   2
IT          25  Age is 25           1

但是,如果验证增加,我必须添加许多 select 查询。

有没有性能更好的替代方法?

你可以使用 cross apply:

select t.*, x.*
from centralfinancetax_im_dev.sallutest t
cross apply (values
    (1, case when t.age = 25 then 'Age is 25' end),
    (2, case when t.age > 29 then 'Age is not in 20s' end),
    (3, case when t.department <> 'IT' then 'Dept not IT' end)
) x(FailedValidationId, FailedValidation)
where x.FailedValidation is not null