首页 > 解决方案 > SQL Server:仅当同一个表中的另一列是特定值时,如何强制一列中的 NOT NULL?

问题描述

我对 SQL 很陌生,因此将不胜感激任何帮助。

我有下表:

在此处输入图像描述

我需要在BusinessNameand上强制 NOT NULL BusinessType,但前提是CustomerType = 'Business'. 我已经在CustomerType列上添加了一个约束,因此只有BusinessorPersonal将被接受。

如果用户要设置个人帐户,则BusinessNameBusinessType列将接受 NULL。

标签: sqlsql-server

解决方案


像这样向现有表添加约束

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
)

推荐阅读