3

我是 T-SQL 新手,请帮忙:我有两个表

User
  Id
  Name

History
  Id
  Result
  UserId

如何创建关系,因此一旦我从用户表中删除用户,历史表将针对列 UserId 更新为 NULL

4

4 回答 4

5

你可以on delete set null这样使用

ALTER TABLE USERS 
ADD CONSTRAINT Users_ThemeID_FK 
FOREIGN KEY (ThemeID) REFERENCES Themes(ThemeID) 
ON DELETE SET NULL
于 2013-03-22T19:20:10.390 回答
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 
于 2013-03-22T19:19:57.853 回答
0

确保打开Cascading deletes,然后设置 pK 关系,然后您只需使用常规 Delete 语法,如Delete From Table Where PK =

于 2013-03-22T19:17:40.590 回答
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/

于 2013-03-22T19:20:10.070 回答