I have the following table schema:
CREATE TABLE saved_custom_view (
[saved_custom_view_id] BIGINT IDENTITY (1, 1) NOT NULL,
[user_id] BIGINT NULL,
[name] NVARCHAR (250) NOT NULL,
[is_default_view] BIT NOT NULL DEFAULT 0
CONSTRAINT [PK__saved_custom_view] PRIMARY KEY CLUSTERED ([saved_custom_view_id] ASC),
CONSTRAINT [FK__saved_custom_view__user] FOREIGN KEY ([user_id]) REFERENCES [user] ([user_id]),
);
I want to make sure that no user has more than one row with is_default_value set to true. Therefore, the second insert here should be prevented with a proper CHECK CONSTRAINT.
insert into saved_custom_view values (1, 'test', 1)
insert into saved_custom_view values (1, 'test', 1)
How do I write a check constraint for this?
ALTER TABLE saved_custom_view
ADD CONSTRAINT CK_no_user_has_duplicate_default_views CHECK (
-- what goes here?
);
Or is there a way to do a unique check against multiple columns?