簡體   English   中英

如何使用復合鍵在SQL Server中進行參照完整性?

[英]How do I do referential integrity in SQL Server with a compound key?

當我運行底部顯示的SQL時,為什么返回:

消息1776,級別16,狀態0,第2行
在引用表“ priceex.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

您需要將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不會從相應表中刪除記錄。

暫無
暫無

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

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