Cascading referential integrity constraint
CREATE TABLE [dbo].[tblDepartment](
[depId] [int] NOT NULL,
[depName] [nvarchar](20) NOT NULL
);
CREATE TABLE [dbo].[tblEmployees](
[empId] [int] IDENTITY(1,1) NOT NULL,
[empName] [nvarchar](20) NOT NULL,
[empEmail] [nvarchar](20) NULL,
[empDepId] [int] NULL
);
INSERT [dbo].[tblDepartment] ([depId], [depName]) VALUES (1, 'ECE');
INSERT [dbo].[tblDepartment] ([depId], [depName]) VALUES (2, 'CSE');
INSERT [dbo].[tblDepartment] ([depId], [depName]) VALUES (3, 'IT');
INSERT [dbo].[tblEmployees] ([empId], [empName], [empEmail], [empDepId]) VALUES (1, 'datta', 'kumar@g.com', 3);
INSERT [dbo].[tblEmployees] ([empId], [empName], [empEmail], [empDepId]) VALUES (3, 'Teja', 'teja@g.com', 1);
--set default
ALTER TABLE tblEmployees
ADD CONSTRAINT df_DepId
DEFAULT 1 FOR empDepId;
delete from tblDepartment where depId=3;
1. No Action: This is the default behaviour. No Action specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, an error is raised and the DELETE or UPDATE is rolled back.
2. Cascade: Specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are also deleted or updated.
3. Set NULL: Specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are set to NULL.
4. Set Default: Specifies that if an attempt is made to delete or update a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are set to default values.
Comments
Post a Comment