Sql-Server
SQL Server - 確保插入時的複雜關係
我有一些相關的表:
Application
- 儲存應用程序列表ApplicationInstall
- 對於每個應用程序,存在多個安裝(我有一個外鍵ApplicationUid
)SecurityPrincipal
- 對於每個ApplicationInstall
我有很多主體(我有一個外鍵ApplicationInstallUid
)。我還有一張表
SecurityPrincipalType
,Application
通過一對多連結。我想要一個規則來保證當我在
SecurityPrincipal
其類型中插入一條記錄時,它來自SecurityPrincipalType
連結到正確的Application
.我沒有重命名這些表,因為我通常更喜歡考慮名稱。但我認為以下場景是等價的:
Table A
n..1Table B
1..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) )