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
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
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
ALTER TABLE dbo.History ADD CONSTRAINT
FK_History_User FOREIGN KEY
(
UserID
) REFERENCES dbo.[User]
(
ID
) ON UPDATE NO ACTION
ON DELETE SET NULL
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 =
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/