【微筆記】SQL Server複合式外部索引條件約束失效的陷阱

SQL Server複合式外部索引(Composite Foreign Key),條件約束失效的陷阱

在SQL Server,資料表若有使用複合式外部索引(Composite Foreign Key),且欄位為可允許為NULL,則會失去條件約束驗證的作用,依官方文件說明如下:
(參考網址:https://docs.microsoft.com/zh-tw/sql/relational-databases/tables/create-foreign-key-relationships?view=sql-server-ver15)

測試

CREATE TABLE [MASTER]
( 
     CODE_ID   varchar(20) NOT NULL, 
     CODE_TYPE int NOT NULL,
     CONSTRAINT PK_MASTER_KEY PRIMARY KEY NONCLUSTERED(CODE_ID, CODE_TYPE)
)
GO

CREATE TABLE DETAIL
( 
    DETAIL_ID INT IDENTITY(1,1) PRIMARY KEY,
     CODE_ID   varchar(20) NULL, 
     CODE_TYPE int NULL
)
GO

ALTER TABLE DETAIL ADD CONSTRAINT FK_CODE_ID_TYPE FOREIGN KEY(CODE_ID, CODE_TYPE)
REFERENCES MASTER (CODE_ID, CODE_TYPE)
GO

-------新增MASTER資料
INSERT INTO [MASTER] VALUES('A', 1)
GO

-------新增DETAIL資料
INSERT INTO DETAIL VALUES(NULL, NULL) -->>成功
GO
INSERT INTO DETAIL VALUES('A', 1) -->>因為MASTER有此組資料,故成功
GO
INSERT INTO DETAIL VALUES('A', 2) -->>因為MASTER無此組資料,失敗
GO
INSERT INTO DETAIL VALUES(NULL, 1) -->>因為MASTER無此組資料,預期會失敗,但卻成功
GO
INSERT INTO DETAIL VALUES(NULL, 2) -->>因為MASTER無此組資料,預期會失敗,但卻成功
GO
INSERT INTO DETAIL VALUES('A', NULL) -->>因為MASTER無此組資料,預期會失敗,但卻成功
GO
INSERT INTO DETAIL VALUES('B', NULL) -->>因為MASTER無此組資料,預期會失敗,但卻成功
GO
SELECT * FROM [MASTER]
SELECT * FROM [DETAIL]
結果

 

 

創用 CC 授權條款
本著作由Chenting Weng製作,以創用CC 姓名標示 4.0 國際 授權條款釋出。
This work by Chenting Weng is licensed under a Creative Commons Attribution 4.0 International License.
Based on a work at https://dotblogs.com.tw/chentingw.

部分文章內容會引用到其他網站的簡介或圖片,若有侵犯到您的著作權,請留言告知,本人會儘快移除。
免責聲明:文章屬個人記事使用,僅供參考,若引用文章造成一切損失,本人不承擔任何責任。如有錯誤,歡迎留言告知。

Part of the content of the article will refer to the profile or picture of other websites.
If there is any infringement of your copyright, please leave a message and let me remove it as soon as possible.
Disclaimer:The article is for personal use and is for reference only. I will not bear any responsibility for any loss caused by quoting the article. If there is an error, please leave a message to inform.