1

Based on Constraint for only one record marked as default would the same approach of a view and unique clustered index apply if I wanted to achieve the same result at a table scope?

I have a table called Accounts. There can be only one System account, however there can be many Partner and Client accounts. Each type of account does not vary in terms of the columns but instead with just the Type column.

ID | Type    | Name 
1    System    Contoso
2    Partner   Wingtip
3    Partner   Northwind
4    Client    Adventure Works
5    Client    Fabrikam

In the above I want to prevent adding another System account, but allow many partner and client accounts. It feels like a concern that belongs in the database as opposed to the domain (maybe I'm wrong)?

Community
  • 1
  • 1
Colin Bowern
  • 2,152
  • 1
  • 20
  • 35

1 Answers1

3

If you know that the system account will always have ID number 1, you can implement this with a CHECK constraint. Something along these lines . . .

create table accounts (
  id integer primary key,
  type varchar(15) not null,
  name varchar(15) not null,
  unique (type, name),
  check (
    (id = 1 and type = 'System') or
    (id <> 1 and type <> 'System')
  )
);

In fact, if this is your database, the system account can have any id number. Just change the CHECK() constraint to match.

If you're building for deployment to a client site, you can add the system account before deployment. (And you probably should, regardless of how you handle the constraints.)

Think about about what to do when a user tries to delete rows from this table. (Especially that system account row.) Then think about what to do when a database admin tries to delete rows from that table.

You can probably use a foreign key constraint (no cascade) or a trigger to prevent a database admin from accidentally deleting the system account. The admin can probably get around those restrictions, but you'd hope she knows what she's doing if she's willing to go that far to delete a row.

Mike Sherrill 'Cat Recall'
  • 91,602
  • 17
  • 122
  • 185
  • Good call - we are in fact adding the system account before the app can be enabled for regular use. As for the back-end data meddling that's another challenge but luckily less so for this environment with strict access controls. – Colin Bowern Apr 09 '12 at 17:27