我在SQL Server 2008中生成了SQL数据库,如下所示:
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);
并希望删除所有ID为&gt的公司; 140000(其他表中的相关行)。我在一个事务中尝试了一些INNER JOIN的组合,但是FK_Client_Company约束仍然存在问题。任何人都可以帮助我吗?
还有一件事 - 我无法添加任何内容/修改数据库结构/约束。它必须是一个基于查询的解决方案。
答案 0 :(得分:0)
首先删除这些公司的客户
delete client where id in (select fk_client_company from company where id > 140000)
之后,您应该能够在公司表
上运行delete语句 delete company where id > 140000
我'确定'这是你正在寻找的答案,但我不是100%肯定,因为你的命名方案似乎有点奇怪。我假设company.fk_client_company = client.id。