我目前有一个select语句,它检查几列以查看它们是否有数据.如果它们中的任何一个为null,那么我想要一个设置为false.如果它们都不为null,那么我想要一个设置为true.这是我现在拥有的:
- select
- cast(
- case when ChangeOrderNumber is null then 0 else 1 end *
- case when ClientName is null then 0 else 1 end *
- case when QuoteNumber is null then 0 else 1 end *
- case when ClientNumber is null then 0 else 1 end *
- case when ServiceLine is null then 0 else 1 end *
- case when ServiceLineCode is null then 0 else 1 end *
- case when GroupLeader is null then 0 else 1 end *
- case when CreatedBy is null then 0 else 1 end *
- case when PTWCompletionDate is null then 0 else 1 end *
- case when BudgetedHours is null then 0 else 1 end *
- case when BudgetDollars is null then 0 else 1 end *
- case when InternalDeadlineDate is null then 0 else 1 end *
- case when ProjectDescription is null then 0 else 1 end *
- case when Sales is null then 0 else 1 end *
- case when Coop is null then 0 else 1 end *
- case when PassThrough is null then 0 else 1 end *
- case when POStatus is null then 0 else 1 end *
- case when PONumber is null then 0 else 1 end as bit
- )
- as Flag
- from t
现在,该代码有效,但它有点冗长,我想知道是否有人知道更好的方法来做到这一点.请注意,有几种数据类型正在检查中.
更多详情:
此代码位于应用程序中用于处理变更单的视图中.在处理变更单之前,它必须满足一些数据质量检查.此视图显示是否有任何所需数据为空.
解决方法
只需添加它们,因为NULL“something”总是为NULL …
- CREATE TABLE #test(column1 int,column2 varchar(4),column3 float)
- INSERT #test VALUES(2,'2',2)
- INSERT #test VALUES(0,'1',0)
- INSERT #test VALUES(null,0)
- INSERT #test VALUES(1,null,0)
- INSERT #test VALUES(0,null)
- INSERT #test VALUES(null,null)
- SELECT CASE
- WHEN column1 + column2 + column3 is NULL THEN 0 ELSE 1 END,*
- FROM #test
从我在3年前创建的post开始……
请记住,如果您的字符不是必须转换为varchar的数字…
- INSERT #test VALUES(0,'abc',null)
这是转换,无需转换varchar列
- SELECT CASE WHEN CONVERT(VARCHAR(100),column1)
- + column2
- +CONVERT(VARCHAR(100),column3) is NULL THEN 0 ELSE 1 END,*
- FROM #test