2015-01-02 65 views
1

我在設置檢查約束時遇到問題。我有表策略,其中主鍵設置在(Policy_id, History_id) +其他列和表報告其中有Policy_id和一些額外的列。SQL集檢查約束條件

如何在Report表上設置檢查約束語句以檢查Policy_id中是否存在policy_id?

我不能使用外鍵約束,因爲報告不具備history_id列

報告不能包含紀錄Policy_id,如果它不存在策略表,因此,不能執行INSERT INTO報告

+0

您可以編寫一個接受Policy_id的函數,並檢查它是否存在於策略表中。 –

回答

0

如果Policy_idHistory_id是複合主鍵,那麼引用表上的外鍵也必須包含這兩列。

如果你真的需要檢查其中的一個(policy_id)我想你必須手動做這不是一個好主意。

如果Report表有2個外鍵,並且policy_idhistory_id都是單個主鍵,會更好。

0

您可以創建一個單獨的表只爲這外鍵約束的目的,然後使用觸發器來維護這樣的數據:

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 

(代碼未經測試,但應接近正確)

0

I認爲使用檢查約束是一個好主意。

編寫一個接受Policy_id作爲參數的函數,並執行查詢來檢查策略是否存在於策略表中,並返回簡單的1(存在)或0(不存在)。

然後設置你的檢查約束,你的報告表,以dbo.MyFunction(Policy_Id)=1

就是這樣。