To elabortate,
is it possible to enforce a rule where ONLY one record entry can have a column named ‘IsPrimaryUser’ set to true, whereas all others grouped by another column are set to false. The condition for deciding which entry will have a true ‘IsPrimaryUser’ field will be the CompanyId column.
I am only interested in whether it can be done using check constraints. Obviously, there is a SQL approach to something like this.
Example:
User Table
int UserId | int CompanyId | bit IsPrimaryUser
Data:
UserId | CompanyId | IsPrimaryUser
1 1 1
2 1 0
3 1 0
4 1 0
5 2 1
6 2 0
7 2 0
8 2 0
Check Constraints only work on a single row, but you can use scalar UDFs within the constraint.
You can breach the single-row check by using UDFs that check other rows in the table. Although unlike a trigger where you can access the DELETED virtual table and process individually, SQL Server seems to hold the records in a sort of transaction, and perform a CHECK on EACH row after the change, then finally accepting or aborting the CRUD in batch.
See this test case
Create table
Populate
Scalar function helper
The CHECK constraint
Tests
(note) I updated the answer after Martin’s comment below