Sql-Server

SQL Server - 確保插入時的複雜關係

  • February 21, 2021

我有一些相關的表:

Application- 儲存應用程序列表 ApplicationInstall- 對於每個應用程序,存在多個安裝(我有一個外鍵ApplicationUidSecurityPrincipal- 對於每個ApplicationInstall我有很多主體(我有一個外鍵ApplicationInstallUid)。

我還有一張表SecurityPrincipalTypeApplication通過一對多連結。

我想要一個規則來保證當我在SecurityPrincipal其類型中插入一條記錄時,它來自SecurityPrincipalType連結到正確的Application.

我沒有重命名這些表,因為我通常更喜歡考慮名稱。但我認為以下場景是等價的:

Table An..1 Table B1..nTable C

我想強制中的一列C僅包含來自的值A,但通過連結B

我正在考慮:

  • 觸發器
  • 外鍵?
  • 應用程序級別檢查(但我希望在數據庫級別進行一些檢查)

我該怎麼辦?

如果您在 上添加唯一約束Application(Id,SecurityPrinicpalType),則可以為此使用外鍵,如下所示:

--drop table if exists ApplicationInstallSecurityPrinicpal
--drop table if exists ApplicationInstall
--drop table if exists Application

go

create table Application
(
 Id int identity not null, 
 SecurityPrincipalType int,
 constraint pk_Apppliction
   primary key (Id),
 constraint ak_Application
   unique(Id,SecurityPrincipalType)
)

create table ApplicationInstall
(
 ApplicationId int not null,
 Id int identity not null,
 constraint pk_ApplicationInstall
   primary key (ApplicationId,Id),
 constraint fk_ApplicationInstall_Application
   foreign key (ApplicationID) 
   references Application(Id)
)


create table ApplicationInstallSecurityPrinicpal
(
 ApplicationId int not null,
 ApplicationInstallId int not null,
 Id int identity not null, 
 SecurityPrincipalType int,
 constraint pk_ApplicationInstallSecurityPrinicpal
   primary key (ApplicationId,ApplicationInstallId,Id),
 constraint fk_ApplicationInstallSecurityPrinicpal_ApplictionInstall
   foreign key (ApplicationId,ApplicationInstallId)
   references Application(ApplicationId,Id)
 constraint fk_ApplicationInstallSecurityPrinicpal_Appliction
   foreign key (ApplicationId,SecurityPrincipalType)
   references Application(Id,SecurityPrincipalType)
)

引用自:https://dba.stackexchange.com/questions/285771