0
我正在使用SQL Server 2016並試圖在刪除上實現級聯。它確實有效,但如果我把代碼放在一個單獨的腳本中就行不通了。將約束放在--subproject
人和--activity
然後再次添加約束的代碼必須位於單獨的文件中。刪除SQL Server級聯
因此,這是在一個文件中
ALTER TABLE dbo.SubProjectPerson
DROP CONSTRAINT SubProjectPerson_SubProject
,這是在另一個文件
ALTER TABLE dbo.SubProjectPerson
ADD CONSTRAINT SubProjectPerson_SubProject
FOREIGN KEY (SubProjectID)
REFERENCES dbo.SubProject(SubProjectID)
ON DELETE CASCADE;
這就是它的工作原理
這裏的唯一途徑是,我有
腳本BEGIN TRY
BEGIN TRANSACTION
--subproject person
ALTER TABLE dbo.SubProjectPersonRole
DROP CONSTRAINT SubProjectPersonRole_SubProjectPerson
ALTER TABLE dbo.SubProjectPersonRole
ADD CONSTRAINT SubProjectPersonRole_SubProjectPerson
FOREIGN KEY (SubProjectPersonID)
REFERENCES dbo.SubProjectPerson(SubProjectPersonID)
ON DELETE CASCADE;
ALTER TABLE dbo.SubProjectPerson
DROP CONSTRAINT SubProjectPerson_SubProject
ALTER TABLE dbo.SubProjectPerson
ADD CONSTRAINT SubProjectPerson_SubProject
FOREIGN KEY (SubProjectID)
REFERENCES dbo.SubProject(SubProjectID)
ON DELETE CASCADE;
--activity
ALTER TABLE dbo.Activity
DROP CONSTRAINT Activity_SubProject
ALTER TABLE dbo.Activity
ADD CONSTRAINT Activity_SubProject
FOREIGN KEY (SubProjectID)
REFERENCES dbo.SubProject(SubProjectID)
ON DELETE CASCADE;
--subproject
ALTER TABLE dbo.SubProjectDocument
DROP CONSTRAINT SubProjectDocument_SubProject
ALTER TABLE dbo.SubProjectDocument
ADD CONSTRAINT SubProjectDocument_SubProject
FOREIGN KEY (SubProjectID)
REFERENCES dbo.SubProject(SubProjectID)
ON DELETE CASCADE;
ALTER TABLE dbo.SubProjectNote
DROP CONSTRAINT SubProjectNote_SubProject
ALTER TABLE dbo.SubProjectNote
ADD CONSTRAINT SubProjectNote_SubProject
FOREIGN KEY (SubProjectID)
REFERENCES dbo.SubProject(SubProjectID)
ON DELETE CASCADE;
--communication thread
ALTER TABLE dbo.CommunicationThread
DROP CONSTRAINT CommunicationThread_SubProjectID
ALTER TABLE dbo.CommunicationThread
ADD CONSTRAINT CommunicationThread_SubProjectID
FOREIGN KEY (SubProjectID)
REFERENCES dbo.SubProject(SubProjectID)
ON DELETE CASCADE;
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH
這個長的腳本運行正常,沒有錯誤,但沒有改變被選中這兩個表,除非我在單獨的文件中運行它們。這裏有什麼問題?
在你所有的'alter'語句之後你不需要分號嗎? – Beth
不,這並不能改變什麼,我不得不拆分此成3個腳本爲它工作 –
嘗試添加打印語句,看看哪一個是沒有得到執行。例如: 打印1 ALTER TABLE SubProjectPersonRole DROP約束SubProjectPersonRole_SubProjectPerson print 1 – James