当我运行底部看到的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 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
则不会从相应的表中删除记录.
您需要添加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
则不会从相应的表中删除记录.