Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server 2008 foreign key on delete set default not working

I am testing different foreign key on delete options. I tired cascade, no action, set null, all works, except set default. SQL SERVER just reports error:

Msg 547, Level 16, State 0, Line 1 The DELETE statement conflicted with the FOREIGN KEY constraint "FK_child_parent". The conflict occurred in database "Test", table "dbo.Test_parent", column 'no'. The statement has been terminated.

create table Test_parent(
    [no] int primary key    
)

CREATE TABLE test_child(
     SUB1 INT,
    [NO] int DEFAULT 0 CONSTRAINT FK_child_parent REFERENCES Test_parent([no]) ON DELETE set default
)

insert into Test_parent values(1),(2)

insert into test_child values(1, 1)
insert into test_child values(2, 1)

delete from Test_parent
like image 551
thotwielder Avatar asked May 03 '26 06:05

thotwielder


1 Answers

You delete your parent table, which triggers the set default in the child. The DB tries to set the child records to their default 0. But there's no 0 record in the parent table, triggering the foreign key violation.

like image 157
Marc B Avatar answered May 07 '26 04:05

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!