简体   繁体   English

如何在SQL Server中更新具有唯一值的表FK列?

[英]How can I update a table FK column with unique value in SQL Server?

I have two tables Departments and Workers . 我有两个表DepartmentsWorkers

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.

相关问题 SQL SERVER,ID 列更新为唯一值 - SQL SERVER, ID column update to unique value 如果未插入任何值,如何为SQL Server中的列字段分配唯一值? - How can i allocate a unique value to a column field in SQL Server, if no value is inserted? 如何修改SQL Server 2008 R2 FK的父表 - How i can modify the Parent table for my Sql server 2008 r2 FK 如何强制 SQL Server 2008 R2 中的整个表的列唯一? - How can I force a column to be unique for an entire table in SQL Server 2008 R2? 如何在一个表中使用另一个表中的FK填充我的FK列? - How can I populate my FK column in one table with the FK from another table? 如何根据SQL Server 2008中另一个表中的值编写更新触发器来更新当前表? - How can I write an update trigger to update the current table based on a value in another table in SQL Server 2008? 如何在SQL Server中更新表并添加列值? - How to update table and add column value in SQL Server? 如何使用 Sql server 中另一个表中值的条件更新表中的值 - How can I update a value in a table using a condition on values in another table in Sql server 是否可以基于sql server中的列值在表中创建分区? - Can I create a partition in table based on column value in sql server? SQL:如果该值为null,如何更新列上的值? - SQL: How can I update a value on a column only if that value is null?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM