简体   繁体   中英

SQL Server 2008 - deleting rows with FK constraints

I've got SQL database in SQL Server 2008 generated as follows:

CREATE TABLE Client ( 
    ID bigint,
    Code varchar(50),
    ClientID int NOT NULL
);
ALTER TABLE Client 
  ADD CONSTRAINT PK_Client PRIMARY KEY CLUSTERED (ClientID);

CREATE TABLE Company ( 
    ID bigint,
    Description nvarchar(100),
    SubsidiaryOf bigint,
    companyID int NOT NULL,
    FK_Client_Company int,
    PK_Company int
);
ALTER TABLE Company 
  ADD CONSTRAINT PK_Company PRIMARY KEY CLUSTERED (companyID);

ALTER TABLE Company 
  ADD CONSTRAINT (ID = ID) FOREIGN KEY (FK_Client_Company) 
      REFERENCES Client (ClientID);

ALTER TABLE Company 
  ADD CONSTRAINT (SubsidiaryOf = ID) FOREIGN KEY (PK_Company) 
      REFERENCES Company (companyID);

CREATE TABLE ContactData ( 
    ID bigint,
    LocationID bigint,
    Contact nvarchar(50),
    contactDataID int NOT NULL,
    PK_Location int
);
ALTER TABLE ContactData 
  ADD CONSTRAINT PK_ContactData PRIMARY KEY CLUSTERED (contactDataID);

ALTER TABLE ContactData 
  ADD CONSTRAINT (LocationID = ID) FOREIGN KEY (PK_Location) 
      REFERENCES Location (locationID);


CREATE TABLE Location ( 
    ID bigint,
    CompanyID bigint,
    Country nvarchar(50),
    ZIPCode nvarchar(50),
    locationID int NOT NULL,
    PK_Company int
);
ALTER TABLE Location 
   ADD CONSTRAINT PK_Location PRIMARY KEY CLUSTERED (locationID);

ALTER TABLE Location 
   ADD CONSTRAINT (CompanyID = ID) FOREIGN KEY (PK_Company) 
       REFERENCES Company (companyID);

And would like to delete all the Companies with ID > 140000 (with related rows in other tables). I tried some combination of INNER JOINs all together in one transaction, but there is still a problem with FK_Client_Company constraint. Can anyone help me?

One more thing - I cannot add anything/modify DB structure/constraints. It has to be a query-base-solution.

First delete those companies' clients

    delete client where id in (select fk_client_company from company where id > 140000)

After that you should be able to run the delete statement on the company table

    delete company where id > 140000

I'm 'fairly' sure that's the answer you're looking for but I'm not a 100% positive only because your naming scheme seems a little odd. I'm making the assumption that company.fk_client_company = client.id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM