Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to create a FK constraint

I have 2 tables:

TableA
------
TableAID INT IDENTITY Primary Key
TableBID INT NULL

I add a unique constraint on TableBID
ALTER TABLE TableAID ADD CONSTRAINT xx UNIQUE ([TableBID])

TableB
------
TableBID INT IDENTITY Primary Key

Now when I delete TableA row, I need TableB's to be deleted as well, so i am trying to add a FK with cascade delete

ALTER TABLE TableB ADD CONSTRAINT yy FOREIGN KEY (TableBID) 
REFERENCES TableA (TABLEBID) ON DELETE CASCADE

But I get this error:

Msg 1788, Level 16, State 0, Line 1
Cascading foreign key 'yy' cannot be created where the referencing column 'TableB.TableBID' is an identity column.
like image 876
DotnetDude Avatar asked Oct 23 '25 04:10

DotnetDude


1 Answers

TableB.TableBID cannot simultaneously be an IDENTITY column (which is calcluated independently) and at the same time be a foreign key from a column in another table.

I think you've got your relationship reversed and actually want:

ALTER TABLE TableA ADD CONSTRAINT yy FOREIGN KEY (TableBID) 
REFERENCES TableB (TABLEBID) ON DELETE CASCADE
like image 186
Joe Stefanelli Avatar answered Oct 25 '25 17:10

Joe Stefanelli



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!