3

I'm designing a database schema, and I'm stuck on one part. Below is a simplified version of my schema. Could someone please explain why the following SQL:

CREATE TABLE Users (
  UserID INT NOT NULL PRIMARY KEY,
  FName VARCHAR(64) NOT NULL,
  LName VARCHAR(64) NOT NULL,
  UName VARCHAR(64) NOT NULL UNIQUE,
  PWord CHAR(32) NOT NULL,
  Role VARCHAR(13) NOT NULL
);

...

CREATE TABLE Sale (
  SaleID INT NOT NULL PRIMARY KEY,
  Book INT NOT NULL REFERENCES Books(BookID) ON DELETE NO ACTION,
  Merchant INT NOT NULL REFERENCES Users(UserID) ON DELETE CASCADE,
  Upload DATETIME NOT NULL,
  Sold BIT NOT NULL,
  Price DECIMAL(10, 2) NOT NULL,
  Condition VARCHAR(9) NOT NULL,
  Written BIT NOT NULL,
  Comments VARCHAR(8000) NULL
);

...

CREATE TABLE Purchases (
  PurchaseID INT NOT NULL PRIMARY KEY,
  Buyer INT NOT NULL REFERENCES Users(UserID) ON DELETE CASCADE,
  Merchant INT NOT NULL REFERENCES Users(UserID) ON DELETE NO ACTION,
  Sale INT NOT NULL REFERENCES Sale(SaleID) ON DELETE CASCADE UNIQUE,
  Time DATETIME NOT NULL
);

... results in this error, and how I can overcome it:

Msg 1785, Level 16, State 0, Line 38
Introducing FOREIGN KEY constraint 'FK__Purchases__Sale__25869641' on table
'Purchases' may cause cycles or multiple cascade paths. Specify ON DELETE
NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

I would like to keep the ON DELETE CASCADE for the Purchases.Sale attribute, if possible.

Thank you for your time.

Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195

1 Answers1

4

Most likely it's because you reference "Users" from two different tables - Buyer in Purchases and Merchant in Sale. The database probably doesn't realize that these two records are never the same - but it knows that it's the same table and therefore complains about a potential issue with cascading.

Arthur Frankel
  • 4,695
  • 6
  • 35
  • 56
  • Hmm... interesting. Any idea on what can be done to overcome this issue? – Oliver Spryn Nov 19 '12 at 02:43
  • 3
    Maybe a trigger. Lots of discussion here: http://stackoverflow.com/questions/1637708/what-is-the-problem-with-foreign-key-cascade-multiple-paths-and-cycles?lq=1 and here: http://stackoverflow.com/questions/851625/foreign-key-constraint-may-cause-cycles-or-multiple-cascade-paths – Arthur Frankel Nov 19 '12 at 02:47
  • Ok... I know triggers are a last resort, but if that is the only method of approach which will solve this problem, then I will take this approach. Thank you, Arthur. – Oliver Spryn Nov 19 '12 at 02:48