表A的PK由表B的FK引用。不能放弃表A的PK

时间:2014-12-09 18:33:43

标签: sql sql-server star-schema

MS SQL Server

我正在制作星型模式。我为我的表设置了PK'sFK,现在我正在尝试编写一个过程来删除约束,截断表,再次添加约束,然后重新填充表。当我尝试删除约束时,我收到错误:

“表PK_TIMEDIM正在引用约束SalesFactTable,外键约束FK_SALESFACTTABLE。无法删除约束。”

编辑:一个问题解决了。另一个发现。我收到相同的错误,但现在有一些神秘的,自动生成的FK's,例如FK__SalesFact__CUST___19DFD96B

请告诉我我做错了什么。

ALTER PROCEDURE [dbo].[A11]
AS
BEGIN

--Drop constraints
ALTER TABLE SalesFactTable
DROP CONSTRAINT FK_SALESFACTTABLE

ALTER TABLE SalesFactTable
DROP CONSTRAINT PK_SALESFACTTABLE

ALTER TABLE TimeDim
DROP CONSTRAINT PK_TIMEDIM

ALTER TABLE CustomerDim
DROP CONSTRAINT PK_CUSTOMERDIM

ALTER TABLE PartDim
DROP CONSTRAINT PK_PARTDIM

--Truncate tables
TRUNCATE TABLE TimeDim
TRUNCATE TABLE CustomerDim
TRUNCATE TABLE PartDim
TRUNCATE TABLE SalesFactTable

--Add constraints
ALTER TABLE TimeDim
ADD CONSTRAINT PK_TIMEDIM PRIMARY KEY (TIME_ID)

ALTER TABLE CustomerDim
ADD CONSTRAINT PK_CUSTOMERDIM PRIMARY KEY (CUST_ID)

ALTER TABLE PartDim
ADD CONSTRAINT PK_PARTDIM PRIMARY KEY (PART_ID)

ALTER TABLE SalesFactTable
ADD CONSTRAINT FK_SALESFACTTABLE FOREIGN KEY (TIME_ID) REFERENCES TimeDim (TIME_ID),
FOREIGN KEY (CUST_ID) REFERENCES CustomerDim (CUST_ID),
FOREIGN KEY (PART_ID) REFERENCES PartDim (PART_ID)

ALTER TABLE SalesFactTable
ADD CONSTRAINT PK_SALESFACTTABLE PRIMARY KEY (TIME_ID, CUST_ID, PART_ID)

1 个答案:

答案 0 :(得分:1)

**外键由主键引用,因此在删除外键约束之前不允许删除主键。 因此,您需要首先删除外键以从表中删除主键约束。

**

ALTER PROCEDURE [dbo].[A11]
AS
BEGIN
  --Drop FK constraints
ALTER TABLE SalesFactTable
DROP CONSTRAINT FK_SALESFACTTABLE
    --Drop PK constraints
ALTER TABLE SalesFactTable
DROP CONSTRAINT PK_SALESFACTTABLE

ALTER TABLE TimeDim
DROP CONSTRAINT PK_TIMEDIM

ALTER TABLE CustomerDim
DROP CONSTRAINT PK_CUSTOMERDIM

ALTER TABLE PartDim
DROP CONSTRAINT PK_PARTDIM

--Truncate tables
TRUNCATE TABLE TimeDim
TRUNCATE TABLE CustomerDim
TRUNCATE TABLE PartDim
TRUNCATE TABLE SalesFactTable

--Add constraints
ALTER TABLE TimeDim
ADD CONSTRAINT PK_TIMEDIM PRIMARY KEY (TIME_ID)

ALTER TABLE CustomerDim
ADD CONSTRAINT PK_CUSTOMERDIM PRIMARY KEY (CUST_ID)

ALTER TABLE PartDim
ADD CONSTRAINT PK_PARTDIM PRIMARY KEY (PART_ID)

ALTER TABLE SalesFactTable
ADD CONSTRAINT FK_SALESFACTTABLE FOREIGN KEY (TIME_ID) REFERENCES TimeDim (TIME_ID),
FOREIGN KEY (CUST_ID) REFERENCES CustomerDim (CUST_ID),
FOREIGN KEY (PART_ID) REFERENCES PartDim (PART_ID)

ALTER TABLE SalesFactTable
ADD CONSTRAINT PK_SALESFACTTABLE PRIMARY KEY (TIME_ID, CUST_ID, PART_ID)