我在设置检查约束时遇到问题。我有表策略,其中主键设置在(Policy_id, History_id)
+其他列和表报告其中有Policy_id
和一些额外的列。SQL集检查约束条件
如何在Report表上设置检查约束语句以检查Policy_id中是否存在policy_id?
我不能使用外键约束,因为报告不具备history_id列
报告不能包含纪录Policy_id
,如果它不存在策略表,因此,不能执行INSERT INTO报告
我在设置检查约束时遇到问题。我有表策略,其中主键设置在(Policy_id, History_id)
+其他列和表报告其中有Policy_id
和一些额外的列。SQL集检查约束条件
如何在Report表上设置检查约束语句以检查Policy_id中是否存在policy_id?
我不能使用外键约束,因为报告不具备history_id列
报告不能包含纪录Policy_id
,如果它不存在策略表,因此,不能执行INSERT INTO报告
如果Policy_id
和History_id
是复合主键,那么引用表上的外键也必须包含这两列。
如果你真的需要检查其中的一个(policy_id
)我想你必须手动做这不是一个好主意。
如果Report
表有2个外键,并且policy_id
和history_id
都是单个主键,会更好。
您可以创建一个单独的表只为这外键约束的目的,然后使用触发器来维护这样的数据:
CREATE TABLE ExistingPolicies (
PolicyID int not null,
PolicyCount int not null,
constraint PK_ExistingPolicies PRIMARY KEY (PolicyID)
)
然后触发器:
CREATE TRIGGER T_Policy_I
on Policy
instead of insert
as
;With totals as (
select PolicyID,COUNT(*) as cnt from inserted
group by PolicyID
)
merge into ExistingPolicies t
using totals s
on
t.PolicyID = s.PolicyID
when matched then update set PolicyCount = PolicyCount + s.cnt
when not matched then insert (PolicyID,PolicyCount) values (s.PolicyID,s.cnt);
go
CREATE TRIGGER T_Policy_D
on Policy
instead of delete
as
;With totals as (
select PolicyID,COUNT(*) as cnt from deleted
group by PolicyID
)
merge into ExistingPolicies t
using totals s
on
t.PolicyID = s.PolicyID
when matched and t.PolicyCount = s.cnt then delete
when matched then update set PolicyCount = PolicyCount - s.cnt;
go
CREATE TRIGGER T_Policy_U
on Policy
instead of update
as
;With totals as (
select PolicyID,SUM(cnt) as cnt
from
(select PolicyID,1 as cnt from inserted
union all
select PolicyID,-1 as cnt from deleted
) t
group by PolicyID
)
merge into ExistingPolicies t
using totals s
on
t.PolicyID = s.PolicyID
when matched and t.PolicyCount = -s.cnt then delete
when matched then update set PolicyCount = PolicyCount + s.cnt
when not matched then insert (PolicyID,PolicyCount) values (s.PolicyID,s.cnt);
go
(代码未经测试,但应接近正确)
I认为使用检查约束是一个好主意。
编写一个接受Policy_id作为参数的函数,并执行查询来检查策略是否存在于策略表中,并返回简单的1(存在)或0(不存在)。
然后设置你的检查约束,你的报告表,以dbo.MyFunction(Policy_Id)=1
就是这样。
您可以编写一个接受Policy_id的函数,并检查它是否存在于策略表中。 –