簡體   English   中英

SQL Server:引用的表中沒有主鍵或候選鍵

[英]SQL Server : there are no primary or candidate keys in the referenced table

我使用SQL Server 2008,當我嘗試在現有數據庫中創建新表時,出現此錯誤:

在引用表“ parceria_conta_corrente_ao”中沒有與外鍵“ R_795”中的引用列列表匹配的主鍵或候選鍵。

該表存在:

在此處輸入圖片說明

我嘗試使用以下代碼創建一個新表:

CREATE TABLE parceria_item_resgate_rateio_aux
( 
    id_parceria_item_resgate_rateio_aux int  NOT NULL IDENTITY,
    dt_conta_corrente    DATETIME  NOT NULL ,
    id_periodo           BIGINT  NOT NULL ,
    id_ao                bigint  NOT NULL ,
    id_gr_cliente        int  NOT NULL ,
    id_cliente           BIGINT  NOT NULL ,
    data_importacao_cli_gr_cli DATETIME  NOT NULL ,
    hp2                  varchar(50)  NOT NULL ,
    hp2_filho            varchar(50)  NOT NULL ,
    valor_nc             decimal(18,2)  NULL ,
    datetime_inclusion   datetime  NOT NULL ,
    status               int  NULL ,
    CONSTRAINT XPKparceria_item_resgate_ PRIMARY KEY  CLUSTERED 
        (id_parceria_item_resgate_rateio_aux ASC, 
        dt_conta_corrente ASC, 
        id_periodo ASC, 
        id_ao ASC, 
        id_gr_cliente ASC, 
        id_cliente ASC, 
        data_importacao_cli_gr_cli ASC, 
        hp2 ASC),
    CONSTRAINT R_795 FOREIGN KEY(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2) 
        REFERENCES parceria_conta_corrente_ao(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
        ON DELETE CASCADE
        ON UPDATE CASCADE
)
go

問題出在哪兒?

您需要在引用表上創建唯一索引:

CREATE UNIQUE INDEX UX_parceria_conta_corrente_ao 
ON parceria_conta_corrente_ao
(
     dt_conta_corrente,
     id_periodo, 
     id_ao, 
     id_gr_cliente, 
     id_cliente, 
     data_importacao_cli_gr_cli, 
     hp2
)

編輯:我想列不按相同的順序,主鍵中的列必須比前鍵中的列以相同的順序。

如果執行以下操作:

CREATE TABLE T
(
    C1 int NOT NULL,
    C2 int NOT NULL,
    PRIMARY KEY (C1, C2)

)

CREATE TABLE T2
(
    id INT NOT NULL,
    C1 int NOT NULL,
    C2 int NOT NULL,
    CONSTRAINT FK1 FOREIGN KEY (C2, C1) REFERENCES T(C2, C1)
)

您收到以下錯誤:

消息1776,級別16,狀態0,第9行,在被引用表'T'中沒有與外鍵'FK1'中的引用列列表匹配的主鍵或候選鍵。 消息1750,級別16,狀態0,第9行無法創建約束或索引。 請參閱先前的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM