sql - SQL Server:仅当同一个表中的另一列是特定值时,如何强制一列中的 NOT NULL?
问题描述
我对 SQL 很陌生,因此将不胜感激任何帮助。
我有下表:
我需要在BusinessName
and上强制 NOT NULL BusinessType
,但前提是CustomerType = 'Business'
. 我已经在CustomerType
列上添加了一个约束,因此只有Business
orPersonal
将被接受。
如果用户要设置个人帐户,则BusinessName
和BusinessType
列将接受 NULL。
解决方案
像这样向现有表添加约束
ALTER TABLE Customers ADD CONSTRAINT Con_First check
(
CustomerType = 'Business' AND BusinessName IS NOT NULL AND BusinessType IS NOT NULL
OR CustomerType <> 'Business' -- BusinessName and BusinessType can be null or not null, we omit AND here
)
推荐阅读
- c# - 带有 Elasticsearch 7.1 的 NEST 7.0 alpha 2 中的 SortField
- chart.js - Chart.js 标签颜色定位在工具提示/图例中
- css - iOS Safari浏览器网站问题(没有高度?)
- sql - 在 SQL 上为函数创建快捷方式
- python - 如何将多个 API 请求写入有效的 JSON 文件?
- java - JMH 基准迭代中的随机峰值
- react-native - 如何在 react-native 中使用淡入打开其他屏幕?
- java - 当我使用意图开始活动时,我的应用程序已停止工作
- r - 获取四分之一圆曲线中的 n 个等距值
- swift - NSURLConnection 以错误结束 - Swift 4 中的代码 -1100