sql server - How can I make child rows delete when I delete a parent row? -


i have following ddl:

create table [dbo].[test] (     [userid]                nvarchar (128) not null,     [testid]                int            identity (1, 1) not null,     [examid]                int            not null,     [title]                 nvarchar (100) null,     [status]                int            not null,     constraint [pk_test] primary key clustered ([testid] asc),     constraint [fk_testexam] foreign key ([examid]) references [dbo].[exam] ([examid]) );   create table [dbo].[testquestion] (     [testquestionid] int           identity (1, 1) not null,     [testid]         int           not null,     [thisanswered]   bit           default ((0)) null,     constraint [pk_testquestion] primary key clustered ([testquestionid] asc),     constraint [fk_testquestion_test] foreign key ([testid]) references [dbo].[test] ([testid]) );   go create nonclustered index [testquestiontest_testid_ix]     on [dbo].[testquestion]([testid] asc); 

i tried delete parent test gives me error. there way can modify automatically deletes records in testquestion table when delete test test table?

you need cascade delete

constraint [fk_testquestion_test] foreign key ([testid]) references [dbo].[test] ([testid])  on delete cascade 

edit

alter table [dbo].[testquestion] drop constraint [fk_testquestion_test];  alter table [dbo].[testquestion] add constraint [fk_testquestion_test] foreign key ([testid]) references [dbo].[test] ([testid]) on delete cascade; 

see sqlfiddle


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -