SQL Server:只有当同一个表中的另一列是特定值时,如何在列中强制使用NOT NULL?

时间:2018-06-17 11:33:03

标签: sql sql-server

我对SQL非常陌生,所以对此的任何帮助都将非常感激。

我有下表:

enter image description here

我需要强制BusinessNameBusinessType上的NOT NULL,但仅限于CustomerType = 'Business'。我已在CustomerType列添加了约束,以便只接受BusinessPersonal

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

3 个答案:

答案 0 :(得分:2)

向现有表添加约束,如此

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
)

答案 1 :(得分:1)

CHECK (( CustomerType = 'Business' AND  BusinessName  is not null) OR CustomerType <> 'Business' )

但是,可以通过将BusinessName等表格移出特定于业务的表格来改进您的架构

答案 2 :(得分:0)

好的谢谢你们 - 点了。

因此,在这种情况下,我会更好:

CREATE TABLE CustomerID  
(
    Cust_ID,
    CustomerType,
);

CREATE TABLE BusinessCustomers 
(
    BusinessName,
    Address,
    etc.
    Cust_ID **FK**
);

CREATE TABLE PersonalCustomers 
(
    CustName,
    Address,
    etc.
    Cust_ID **FK**
);