如何查看一个表并使用它来检查另一个表的数据完整性?
我有两个SQL表。
一个人表
CREATE TABLE PERSON
(
ID INT IDENTITY(10000,1) NOT NULL,
Firstname VARCHAR(15),
Lastname VARCHAR(25) NOT NULL,
Birthdate DATE,
Gender VARCHAR(1),
CHECK ( GENDER IN ('M', 'F')),
Street VARCHAR(50),
City VARCHAR(15),
State VARCHAR(2),
CHECK (State IN ('FL','GA','PA')),
Zip INT,
Phone VARCHAR(10),
Employee VARCHAR(1),
CHECK ( Employee IN('Y','N')),
Member VARCHAR(1),
CHECK ( Member IN('Y','N')),
CHECK (Member IN ('Y') or Employee IN ('Y')),
CONSTRAINT PERSON_PK PRIMARY KEY (ID));
和员工表
CREATE TABLE EMPLOYEE
(
ID INT NOT NULL,
Datehired DATE DEFAULT GETDATE(),
Status VARCHAR(1),
CHECK ( Status IN ('F','C')),
Position VARCHAR(25),
EmpType VARCHAR(25),
CONSTRAINT EMPLOYEE_PK PRIMARY KEY (ID),
CONSTRAINT EMPLOYEE_PERSON_FK FOREIGN KEY (ID) REFERENCES PERSON);
让我们说某人不是雇员。我仍然可以将它们插入到员工表中。
INSERT INTO EMPLOYEE
(ID, Status, Position, EmpType)
VALUES
('10000','C','Teaching Classes','Instructor');
如何防止这种情况发生。
答案 0 :(得分:1)
一种方法是使用冗余密钥:
alter table person
contraint unq_person_id_employee
unique (id, employee);
然后将一个计算列添加到employee:
alter table employee add employee as ('Y') persisted;
最后,添加约束:
alter table employee
add constraint fk_employee_person
foreign key (id, employee) references person(id, employee);
现在,您可以保证只有员工在Employee
表中。