SQL Server:引用的表中没有主键或候选键

时间:2015-03-09 14:00:59

标签: sql sql-server

我使用SQL Server 2008,当我尝试在现有数据库中创建新表时,会出现此错误:

  

引用表'parceria_conta_corrente_ao'中没有主键或候选键与外键'R_795'中的引用列列表匹配。

此表存在:

enter image description here

我尝试用这段代码创建一个新表:

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

问题出在哪里?

1 个答案:

答案 0 :(得分:3)

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

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
)

编辑: 我猜这些列的顺序不一样,主键中的列必须与foreing键中的列的顺序相同。

如果执行以下操作:

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)
)

您收到以下错误:

  

Msg 1776,Level 16,State 0,Line 9没有小学或候选人   引用表中的键' T'与引用列匹配   列出外键' FK1'。 Msg 1750,Level 16,State 0,Line 9   无法创建约束或索引。查看以前的错误。