在删除northwindcs表时,发生报错,消息 3726,级别 16,状态 1,第 2 行,无法删除对象 '产品',因为该对象正由一个 FOREIGN KEY 约束引用。此时判断是因为有其他表的外键引用了本表,导致无法删除。下面脚本可查询本表是由哪个表的哪个外键引用:
SELECT FK.NAME,FK.OBJECT_ID,OBJECT_NAME(FK.PARENT_OBJECT_ID) AS REFERENCETABLENAME
FROM SYS.FOREIGN_KEYS AS FK
JOIN SYS.OBJECTS AS O ON FK.REFERENCED_OBJECT_ID=O.OBJECT_ID
WHERE O.NAME = '产品'
得到如下结果,订单明细表上有一各名为‘FK_订单明细_产品’的外键引用了产品表,
NAME | OBJECT_ID | REFERENCETABLENAME |
FK_订单明细_产品 | 1.416E+09 | 订单明细 |
删除订单明细表的该外键,就可删除产品表:
ALTER TABLE dbo.订单明细 DROP CONSTRAINT FK_订单明细_产品