Sergey
Sergey

Reputation: 8091

How to create foreign key so when we delete parent value in child will be updated 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

Upvotes: 3

Views: 510

Answers (4)

Sachin
Sachin

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

Rikon
Rikon

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

bummi
bummi

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

Vortex
Vortex

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

Related Questions