[英]How can I update a table FK column with unique value in SQL Server?
I have two tables Departments
and Workers
. 我有两个表
Departments
和Workers
。
Departments
table has a ManagerID
column. Departments
表有一个ManagerID
列。 I choose managerID from Workers.ID
and add to Departments.ManagerID
but no one can be manager of different departments at the same time. 我从
Workers.ID
选择managerID并添加到Departments.ManagerID
但是没有人可以同时成为不同部门的经理。 How can I control it in an update query? 如何在更新查询中控制它?
Departments table 部门表
Workers table 工人桌
If you want to block managers from being manager for more than one department than the easiest way is to create an unique index on the Departments table on the column ManagerID 如果您希望阻止管理员成为多个部门的经理,那么最简单的方法是在ManagerID列上的Departments表上创建唯一索引
create unique nonclustered index UX_ManagerID on Departments (ManagerID)
where ManagerID is NOT NULL;
Now all updates and inserts that attempt to make a manager the boss of more than one department will fail. 现在,所有试图使经理成为多个部门的老板的更新和插入都将失败。 In the error message the name 'UX_ManagerID' will be present so you can check that in the exception message and give a nice message to the user.
在错误消息中将出现名称“UX_ManagerID”,以便您可以在异常消息中检查该消息并向用户发送一条消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.