Jan*_*ngo 5 sql t-sql sql-server
我需要清除许多表(最好是截断表).但是表有许多FK约束.我试过这样的事,但失败了: -
ALTER TABLE Table1 NOCHECK CONSTRAINT ALL
TRUNCATE TABLE Table1
ALTER TABLE Table1 WITH CHECK CHECK CONSTRAINT ALL
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误: -
无法截断表'Test',因为它正被FOREIGN KEY约束引用.
请通过临时删除约束建议我如何删除或截断表.
只需按正确的FK顺序删除它们:
DELETE GreatGrandChild
DELETE Child
DELETE Parent
Run Code Online (Sandbox Code Playgroud)
并且不用担心放弃约束.
示例代码:
create table ParentTable (ParentID int primary key not null, RowValue varchar(10))
INSERT INTO ParentTable VALUES (1,'AAA')
INSERT INTO ParentTable VALUES (2,'BBB')
create table ChildTable (ChildID int primary key not null, ParentID int, RowValue varchar(10))
ALTER TABLE ChildTable ADD CONSTRAINT FK_ChildTable_ParentTable FOREIGN KEY
(ParentID) REFERENCES dbo.ParentTable (ParentID) ON UPDATE NO ACTION ON DELETE NO ACTION
INSERT INTO ChildTable VALUES (10,1,'a')
INSERT INTO ChildTable VALUES (11,1,'aa')
INSERT INTO ChildTable VALUES (12,2,'b')
INSERT INTO ChildTable VALUES (13,1,'aaa')
DELETE ChildTable
DELETE ParentTable
Run Code Online (Sandbox Code Playgroud)
要查找依赖于表的表,请运行此查询:
select
object_name(parent_object_id) AS ReferencesYourTable
,object_name(referenced_object_id) AS YourTable
,*
from sys.foreign_keys
WHERE object_name(referenced_object_id)='YourTable'
Run Code Online (Sandbox Code Playgroud)
对于上述查询,删除在删除YourTable之前列出的每个表中的所有行.