SQL集检查约束
我在设置“检查约束”时遇到问题。我有一个表Policy,其中主键设置在Policy\u id、History\u id+附加列上,表Report有Policy\u id和一些附加列 如何在报表表上设置check constraint语句以检查策略表中是否存在策略id 我无法使用外键约束,因为报表没有“历史记录\u id”列 如果策略表中不存在具有策略id的记录,则报表不能包含该记录,因此无法执行插入到报表中如果策略id和历史id是复合主键,则引用表上的外键也必须同时包含这两列 如果你真的只需要检查其中一个策略id,我想你必须手动执行,这不是一个好主意SQL集检查约束,sql,sql-server,tsql,Sql,Sql Server,Tsql,我在设置“检查约束”时遇到问题。我有一个表Policy,其中主键设置在Policy\u id、History\u id+附加列上,表Report有Policy\u id和一些附加列 如何在报表表上设置check constraint语句以检查策略表中是否存在策略id 我无法使用外键约束,因为报表没有“历史记录\u id”列 如果策略表中不存在具有策略id的记录,则报表不能包含该记录,因此无法执行插入到报表中如果策略id和历史id是复合主键,则引用表上的外键也必须同时包含这两列 如果你真的只需要检
如果报表表有2个外键,并且策略id和历史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
代码未经测试,但应该接近正确我认为在这里使用检查约束是一个好主意 编写一个函数,接受Policy_id作为参数,并执行查询以检查Policy表中是否存在该策略,并返回一个简单的1 exists或0 notexists 然后将报表表上的检查约束设置为dbo.MyFunctionPolicy\u Id=1
就是这样。您可以编写一个函数,接受策略id并检查它是否存在于策略表中。