我是 T-SQL 新手,请帮忙:我有两个表
User
Id
Name
History
Id
Result
UserId
如何创建关系,因此一旦我从用户表中删除用户,历史表将针对列 UserId 更新为 NULL
我是 T-SQL 新手,请帮忙:我有两个表
User
Id
Name
History
Id
Result
UserId
如何创建关系,因此一旦我从用户表中删除用户,历史表将针对列 UserId 更新为 NULL
你可以on delete set null
这样使用
ALTER TABLE USERS
ADD CONSTRAINT Users_ThemeID_FK
FOREIGN KEY (ThemeID) REFERENCES Themes(ThemeID)
ON DELETE SET NULL
ALTER TABLE dbo.History ADD CONSTRAINT
FK_History_User FOREIGN KEY
(
UserID
) REFERENCES dbo.[User]
(
ID
) ON UPDATE NO ACTION
ON DELETE SET NULL
确保打开Cascading deletes,然后设置 pK 关系,然后您只需使用常规 Delete 语法,如Delete From Table Where PK =
您可以将 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/