sql-server - Delete sql rows with fk in another table
问题描述
I have an example uni database where I am required to update department for the new year. I have the following tables
Table 1 (Department) has the following columns:
ID | NAME | SCHOOL | ACTIVE | SNAPSHOT
860 | SOF | 20 | 1 | NULL
861 | CS | 20 | 1 | NULL
ID is PK, int, NOT NULL
Table 2 (User) has the following columns:
ID | EMPNO | FORENAME | SURNAME | DEPT
1495 | e3456 | Parker | Sal | 860
Dept is a FK
Problem:
The two departments in Table 1 should be updated to a single department as below:
ID | NAME | SCHOOL | ACTIVE | SNAPSHOT
860 | School of Sciences | 20 | 1 | NULL
I am using the following sql command :
DELETE FROM Department WHERE ID = 861
And receiving the following error:
Msg 547, Level 16, State 0, Line 10 The DELETE statement conflicted with the REFERENCE constraint "FK__User__Dept". The conflict occurred in database "uniDB", table "dbo.User", column 'Dept'.
Using the same command I am unable to delete the Dept ID 861 from table 2 (User) since a third table has FK constraint User and therefore, I get the same error as above.
Thanks for your help in advance
解决方案
更改链接,然后删除:
UPDATE u SET
Dept = 860
FROM User u
WHERE u.Dept = 861
DELETE d
FROM Department d
WHERE d.ID = 861
推荐阅读
- sql-server - SSIS 中的 INSERT/UPDATE 条件拆分工作不正确
- gstreamer - 使用 gstreamer 播放 Doorbird 音频流
- rsa - 在 Hyperledger Fabric 中使用的外部 x509 证书签名和密钥算法的要求
- node.js - Node.js mongoDB 将新元素推送到现有对象的问题
- flutter - Flutter:手机底部导航栏隐藏的内容
- javascript - 在不渲染视图的情况下调用 cakephp 2 控制器函数(autoRender false 不起作用)
- reactjs - 数组以 Excel React
- php - 阻止 PHP 异常转义 html
- node.js - 如何使用 NodeJS 或 Rest 创建 Google API 密钥?
- javascript - 逐渐接近一个数字而不达到它的算法