What is the best way to handle this constraint in SQL Server 2005?

advertisements

I have SMS based survey application which takes in a survey domain, and a answer.

I've gotten requests for detailed DDL, so.... The database looks like this

SurveyAnswer.Answer must be unique within all active Surveys for that SurveyDomain. In SQL terms, this should always return 0..1 rows:

select * from survey s, surveyanswer sa
where s.surveyid = sa.surveyid and
      s.active = 1 and
      s.surveydomainid = @surveydomainid
      sa.answer = @answer

I plan on handling this constraint at the application level, but would also like some database integrity to be enforced. What is the best way to do this? Trigger? Possible in a constraint?


As you are covering 2 tables there is AFAIK only 2 ways to enforce this.

  1. Trigger as you suggested.
  2. Indexed view with unique constraint accross the 3 columns.

As far as reliability is concerned I would go for the Indexed view but the only downside is that it will be difficult to understand by third parties.