开发者

Enforce Data-Driven 1:1 Constraint on 1:M Relationship

Using SQL Server 2K8 R2, I have two related tables - Member and Questionnaire. Each table has a BigInt PK called ID. Questionnaire has M开发者_运维问答emberID to relate back to the member who is in the process of completing the form. Over time, a member may complete the questionnaire many times. The business requirement is that each member complete a questionnaire at most once per year. AFAIK this can't be solved using a simple CHECK CONSTRAINT.

Is there is "clean" way to do this? I'm hoping to avoid doing something like the following:

CREATE TRIGGER tr_Questionnaire_Insert
  ON Questionnaire
  INSTEAD OF INSERT
AS BEGIN
  -- Check for a violation of once questionnaire per calendar year and if found, call RAISERROR

  -- Otherwise continue with INSERT
END;

The reason I don't want to use this approach is primarily because it requires me (or whomever will be maintaining this solution in the long-term) to remember to maintain the trigger if the schema for Questionnaire should change.


Just create a unique index on the the questionnaire table that includes MemberId and year.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜