sql - How to check if column has value if another column is populated in SQL Server?
问题描述
I am trying to find a way to see if I can write a query to check a table to return any row that is missing a dependency if that makes sense. For example let's say I have the following columns:
EffectiveDate Change1 Change2 Change3
If EffectiveDate has a value, then either Change1, Change2, or Change3 must also have a value since EffectiveDate has a value. Also vice versa, if columns Change1, Change2, or Change3 have a value, then EffectiveDate must have a value.
I need the query to return any rows where it doesn't meet the criteria above and show the columns as NULL so that I know which records to go in to fix any missing values.
So far I've only got the below, it's not much but I can't seem to put the logic together from here. I assume I will need nested CASE statements?:
SELECT employee,
EffectiveDate,
Change1,
Change2,
Change3,
CASE WHEN EffectiveDate IS NOT NULL OR EffectiveDate != ''
THEN ...
FROM table1
解决方案
You seem to want a check
constraint:
alter table table1 add constraint chk_effectivedate_changes
check ( (EffectiveDate is null and Change1 is null and Change2 is null and Change3 is null) or
(EffectiveDate is not null and (Change1 is not null or Change2 is not null or Change3 is not null)
)
);
推荐阅读
- spring-boot - 获取 java.nio.file.NoSuchFileException: ....\asm-all-repackaged.jar
- c++ - 解锁被另一个线程锁定的互斥锁
- php - 未找到 DocuSign PHP 快速入门代码类“DocuSign\eSign\ApiClient”
- c# - 如何在 xamarin iOS 中的 UiKit 中获取一个简单的初始边框
- java - Android 套接字安全异常
- swiftui - 如何在 SwiftUI 中设置 SF Symbol 的大小?
- android - 如果找不到对象,为什么流动不返回任何数据
- amazon-web-services - 经过身份验证的登录后出现 AWS Cognito NotAuthorizedException“无效访问令牌”错误
- javascript - 如何在 react-native 中控制打开/关闭模式
- javascript - Firebase on change 事件。如何知道谁更改了数据?