当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何使用复合键在SQLServer中执行参照完整性?》经验,为你挑选了1个好方法。

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

消息1776,级别16,状态0,行2
在引用的表'pricedex.table_a'中没有与外键'FK_delete_from_parent'中的引用列列表匹配的主键或候选键.

消息1750,级别16,状态0,行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

Lukasz Szozd.. 5

您需要添加PRIMARY KEYtable_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则不会从相应的表中删除记录.



1> Lukasz Szozd..:

您需要添加PRIMARY KEYtable_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则不会从相应的表中删除记录.

推荐阅读
保佑欣疼你的芯疼
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有