我对SQL非常陌生,所以对此的任何帮助都将非常感激。
我有下表:
我需要强制BusinessName
和BusinessType
上的NOT NULL,但仅限于CustomerType = 'Business'
。我已在CustomerType
列添加了约束,以便只接受Business
或Personal
。
如果用户想要设置个人帐户,则BusinessName
和BusinessType
列中将接受NULL。
答案 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**
);