交叉引用另一个值的表值以允许插入

时间:2016-11-16 02:33:27

标签: sql sql-server

如何查看一个表并使用它来检查另一个表的数据完整性?

我有两个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');

如何防止这种情况发生。

1 个答案:

答案 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表中。