简体   繁体   English

外键上的SQL约束

[英]SQL constraint on a foreign key

I am having problems creating a constraint for a foreign key field, so that a foreign key can only be entered if that foreign key links to a row containing a specific attribute. 我在为外键字段创建约束时遇到问题,因此只有在该外键链接到包含特定属性的行时才能输入外键。

To give a better idea about what I mean, I have created the following example. 为了更好地理解我的意思,我创建了以下示例。 The Employee entity table contains a Grade field, which can either be 'S' for a senior level employee, or 'J' for a junior level employee. Employee实体表包含一个Grade字段,对于高级员工,可以为'S',对于初级员工可以为'J'。 In the Expenses table, I want to limit any entries into the ApprovedBy field to those EmpNo values that have a Grade field containing 'S' in the Employee table. 在“ Expenses表中,我想将“ ApprovedBy Employee ”字段中的所有条目限制为“ Employee表中“ Grade字段包含“ S”的那些EmpNo值。

CREATE TABLE Employee
(EmpNo INT PRIMARY KEY,
FirstName VARCHAR(15),
LastName VARCHAR(15),
Grade CHAR(1),
CONSTRAINT chk_ValidGrade CHECK (Grade IN ('J','S'))
)

CREATE TABLE Expenses
(ExpenseId INT IDENTITY(1,1) PRIMARY KEY,
Amount FLOAT,
ApprovedBy INT FOREIGN KEY REFERENCES Employee(EmpNo),
)

I instinctively want to use a join, or other relational algebra function to do this. 我本能地希望使用联接或其他关系代数函数来执行此操作。 However, my understanding is that you can't use the SELECT function within a CHECK function, so I'm not sure how I would define the constraint. 但是,我的理解是您不能在CHECK函数中使用SELECT函数,因此我不确定如何定义约束。

As far as I know, you cannot use check constraint for this task. 据我所知,您不能为此任务使用检查约束。 You have to use a trigger for insert and update in your Expenses table. 您必须使用触发器在“费用”表中进行插入和更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM