Reputation: 8091
I am new in T-SQL please help: I have two tables
User
Id
Name
History
Id
Result
UserId
How to create relationship so once I delete User from User table the History table will be updated for the column UserId to NULL
Upvotes: 3
Views: 510
Reputation: 40980
You can use on delete set null
like this
ALTER TABLE USERS
ADD CONSTRAINT Users_ThemeID_FK
FOREIGN KEY (ThemeID) REFERENCES Themes(ThemeID)
ON DELETE SET NULL
Upvotes: 5
Reputation: 2706
You can change the action on the FK relationship to set to 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
See Here: http://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/
Upvotes: 0
Reputation: 27385
ALTER TABLE dbo.History ADD CONSTRAINT
FK_History_User FOREIGN KEY
(
UserID
) REFERENCES dbo.[User]
(
ID
) ON UPDATE NO ACTION
ON DELETE SET NULL
Upvotes: 1
Reputation: 653
Make sure to turn on Cascading deletes, then setup a pK relationship then you just use regular Delete syntax like Delete From Table Where PK =
Upvotes: 0