我有一个与地址表有一对多关系的客户表。我想限制数据库,以便拥有地址的客户始终拥有一个(并且只有一个)默认地址。
我可以很容易地添加一个约束来确保每个客户只有一个默认地址。然而,我在如何应用确保始终将地址标记为默认地址的约束方面苦苦挣扎。
总结一下:
- 客户不需要有任何地址。
- 如果客户有地址,则必须有默认地址。
- 每个客户只能有一个默认地址。
这是问题的示例和一些“单元”测试。我正在使用链接表来连接客户和地址。
CREATE TABLE Customer
(
Id INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL
)
CREATE TABLE [Address]
(
Id INT PRIMARY KEY,
Address VARCHAR(500) NOT NULL
)
CREATE TABLE CustAddress
(
CustomerId INT,
AddressId INT,
[Default] BIT NOT NULL,
FOREIGN KEY (CustomerId) REFERENCES Customer(Id),
FOREIGN KEY (AddressId) REFERENCES [Address](Id)
)
INSERT INTO Customer VALUES (1, 'Mr Greedy')
INSERT INTO [Address] VALUES (1, 'Roly-Poly House, Fatland')
INSERT INTO [Address] VALUES (2, 'Giant Cottage, A Cave')
-- Should succeed
INSERT INTO CustAddress VALUES (1, 1, 1)
INSERT INTO CustAddress VALUES (1, 2, 0)
DELETE FROM CustAddress
-- Should fail as no default address set
INSERT INTO CustAddress VALUES (1, 1, 0)
DELETE FROM CustAddress
-- Should fail as we end up with no defualt address set
INSERT INTO CustAddress VALUES (1, 1, 1)
INSERT INTO CustAddress VALUES (1, 2, 0)
UPDATE CustAddress SET [Default] = 0 WHERE CustomerId = 1 AND AddressId = 1
DELETE FROM CustAddress
-- Should fail as we end up with no defualt address set
INSERT INTO CustAddress VALUES (1, 1, 1)
INSERT INTO CustAddress VALUES (1, 2, 0)
DELETE FROM CustAddress WHERE CustomerId = 1 AND AddressId = 1