我是T-SQL的新手,请帮忙: 我有两张桌子
User
Id
Name
History
Id
Result
UserId
如何创建关系,一旦我从User表中删除User,将为UserId列更新历史表为NULL
答案 0 :(得分:5)
您可以像这样使用on delete set null
ALTER TABLE USERS
ADD CONSTRAINT Users_ThemeID_FK
FOREIGN KEY (ThemeID) REFERENCES Themes(ThemeID)
ON DELETE SET NULL
答案 1 :(得分:1)
ALTER TABLE dbo.History ADD CONSTRAINT
FK_History_User FOREIGN KEY
(
UserID
) REFERENCES dbo.[User]
(
ID
) ON UPDATE NO ACTION
ON DELETE SET NULL
答案 2 :(得分:0)
确保打开Cascading deletes,然后设置pK关系,然后您只需使用常规删除语法,如Delete From Table Where PK =
答案 3 :(得分:0)
您可以将FK关系上的操作更改为null:
-- Create FK relationship
IF EXISTS (SELECT * FROM sys.objects
WHERE name = N'FK_EmpEducation_Employees' AND [type] = 'F')
ALTER TABLE EmpEducation
DROP Constraint FK_EmpEducation_Employees
GO
ALTER TABLE EmpEducation
ADD CONSTRAINT [FK_EmpEducation_Employees]
FOREIGN KEY (empno)REFERENCES employees(empno)
ON DELETE SET NULL ON UPDATE SET NULL
GO
见这里:http://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/