Home > Database > Mysql Tutorial > How to Ensure Only One Record Has isDefault = 1 in a SQL Server Table?

How to Ensure Only One Record Has isDefault = 1 in a SQL Server Table?

Mary-Kate Olsen
Release: 2025-01-01 03:20:10
Original
158 people have browsed it

How to Ensure Only One Record Has isDefault = 1 in a SQL Server Table?

Constraint for Only One Record Marked as Default

How can a constraint be set on a table so that only one of the records has its isDefault bit field set to 1?

Solution: Using a Unique Filtered Index

For SQL Server 2008 or later, a unique filtered index can be used:

CREATE UNIQUE INDEX IX_TableName_FormID_isDefault
ON TableName(FormID)
WHERE isDefault = 1
Copy after login

where the table is defined as follows:

CREATE TABLE TableName(
    FormID INT NOT NULL,
    isDefault BIT NOT NULL
)
Copy after login

Inserting multiple rows with the same FormID and isDefault set to 1 will result in the following error:

Cannot insert duplicate key row in object 'dbo.TableName' with unique
index 'IX_TableName_FormID_isDefault'. The duplicate key value is (1).
Copy after login

The above is the detailed content of How to Ensure Only One Record Has isDefault = 1 in a SQL Server Table?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template