问题描述
假设我有2个表,Employee
和Sale
。
Employee
表具有EMP_ID
个int作为PK和ACTIVE_STATUS
位(0表示无效,1表示活跃)。
Sale
表具有SALE_ID
作为PK,EMP_ID
作为FK引用了Employee.EMP_ID
和DATE_OF_SALE
现在,我需要一个约束来检查我要插入到EMP_ID
中的Sale
的{{1}}列中的ACTIVE
的值是否为1表格,因为我不想注册闲置用户尝试进行的销售。
我该怎么做?我尝试过Employee
,但这不是有效的声明。
解决方法
您可以使用外键和计算列来完成您特别要求的操作。首先,在employees
中定义一个冗余的唯一约束:
alter table employees add constraint unq_employees_empid_active_status on (empid,active_status);
然后,在sales
中定义一个计算列。 think,我认为这需要坚持下去。
alter table sales add active_status as (convert(bit,1)) persisted;
然后,使用以下两种方法定义外键约束:
alter table sales add foreign key fk_sales_employees_active
foreign key (empid,active_status) references employees(empid,active_status);
Voila!员工ID只能引用在职员工。
现在,您将对此有疑问-请小心您的要求。这不是您真正想要的。这会在所有时间内强制执行约束 。因此,您将无法更改有销售人员的状态。这表明您需要插入触发器,或者使用用户定义的函数和check
约束:
create function is_employee_active (
@empid int
) returns bit as
begin
return (select active_status from employees e where e.empid = @empid);
end;
alter table sales add constraint chk_sales_employee_active
check (is_employee_active(empid) = convert(bit,1));
Voila!这仅对插入或更新进行检查。请注意,一旦员工不活跃,您也将无法更新该行。
您会注意到,我通常将表命名为复数形式,因为它们包含许多实体示例。在考虑表格时,我的手指只会加上“ s”。