如何使用复合键在SQL Server中执行参照完整性?

时间:2015-12-01 16:08:52

标签: sql sql-server tsql

当我运行底部看到的SQL时,为什么会返回:

  

Msg 1776,Level 16,State 0,Line 2
  引用表'pricedex.table_a'中没有主键或候选键与外键'FK_delete_from_parent'中的引用列列表匹配。

     

Msg 1750,Level 16,State 0,Line 2
  无法创建约束。查看以前的错误。

代码:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE table_a 
(
    [column_1] [int] NULL,
    [column_2] [int] NULL
)

CREATE TABLE table_b 
(
    [column_1] [int] NULL,
    [column_2] [int] NULL
)

GO

CREATE NONCLUSTERED INDEX IX_app ON table_a (column_1, column_2)
GO

CREATE NONCLUSTERED INDEX IX_app ON table_b (column_1, column_2)
GO

SET ANSI_PADDING OFF
GO

ALTER TABLE table_b WITH CHECK
ADD CONSTRAINT FK_delete_from_parent 
    FOREIGN KEY (column_1, column_2) REFERENCES table_a (column_1, column_2) 
       ON DELETE CASCADE
GO

1 个答案:

答案 0 :(得分:5)

您需要将PRIMARY KEY添加到table_a并将PK列更改为NOT NULL

CREATE TABLE table_a (
    [column_1] [int] NOT NULL,
    [column_2] [int] NOT NULL,
    PRIMARY KEY(column_1, column_2)            -- compound primary key
);

CREATE TABLE table_b (
    [column_pk] [int] NOT NULL PRIMARY KEY,    -- you probably want different pk
    [column_1] [int] NULL,
    [column_2] [int] NULL
);

-- adding foreign key constraint
ALTER TABLE table_b WITH CHECK
ADD CONSTRAINT FK_delete_from_parent FOREIGN KEY (column_1, column_2)
REFERENCES table_a (column_1, column_2) ON DELETE CASCADE;

SqlFiddleDemo

修改

Create Foreign Key Relationships

  

外键约束不必仅链接到主键   另一个表中的键约束;它也可以定义为参考   另一个表中 UNIQUE约束的列

CREATE TABLE table_a (
    [column_1] [int] NOT NULL,           -- with UNIQUE column can be nullable
    [column_2] [int] NOT NULL,
    UNIQUE(column_1, column_2)
    -- anyway this table should have PK
);

SqlFiddleDemo2

请注意,如果列可以为空并且您有NULL个值ON DELETE CASCADE,则不会从相应的表中删除记录。