【发布时间】:2016-04-04 17:15:49
【问题描述】:
在 Microsoft SQL Server 中,假设我有以下表格:
CREATE TABLE dbo.Employee
(
ID int not null,
Name varchar(50) not null
)
CREATE TABLE dbo.EmployeeAddress
(
ID int not null,
EmployeeID int not null,
Address varchar(50) not null
)
CREATE TABLE dbo.Paycheck
(
ID int not null,
EmployeeID int not null,
AddressID int not null,
Checkdate datetime not null,
Amount money not null
)
我知道我可以创建外键来确保 EmployeeAddress 中的employeeid 存在于Employee 表中,并且我可以创建外键来确保Paycheck 中的employeeid 和addressid 存在于它们各自的表中。我想知道的是,我是否可以创建一个约束来确保 Paycheck 中的 EmployeeID 与 Paycheck 中的 AddressID 的 EmployeeAddress 中的 EmployeeID 匹配?
是的,我意识到我可以从 Paycheck 表中删除 EmployeeID 并解决问题,但我的真实结构(与员工或其薪水无关)要复杂得多,并且不允许这样做。
【问题讨论】:
-
理想的结构是在 Paycheck 中使用 EmployeeAddressID;如果有什么不对的地方,你需要改正
-
您可以使用触发器来实现;在 Paycheck 上编写一个触发器以插入以验证您的自定义逻辑
标签: sql-server