开发者

SQL Server unique constraint (but only sometimes)

开发者 https://www.devze.com 2023-01-18 17:37 出处:网络
Imagine I have a table with 3 columns: ID (unique ID) Description (varchar 2000) IsDeleted (boolean) I want to add a unique constraint so that all descriptions are unique. BUT only for active record

Imagine I have a table with 3 columns:

ID (unique ID) Description (varchar 2000) IsDeleted (boolean)

I want to add a unique constraint so that all descriptions are unique. BUT only for active records i.e. IsDelete = false. If a user flags a record as deleted, they can re-add a record with the same description as a deleted record, but not the same as a active record.

So, I only want the constraint to effect record whe开发者_如何学JAVAre IsDeleted = false.

Tim


In SQL 2008 you can do this using unique index with a filter:

CREATE UNIQUE NONCLUSTERED INDEX ix_table_UNC ON table(Description) WHERE IsDeleted = 0

Pre-SQL 2008, you'd need to create the unique index on a view of the table selecting only the non-deleted records:

CREATE VIEW dbo.vw_ActiveDescriptions WITH SCHEMABINDING
AS
SELECT Id, Description
FROM Table
WHERE IsDeleted= 0
GO
CREATE UNIQUE CLUSTERED INDEX ix_vw_ActiveDescriptions_UC ON dbo.vw_ActiveDescriptions(Description);


Create a new table for the deleted rows. Then enforce uniqueness with a UNIQUE constraint. You would have to make Description smaller because the maximum key size in SQL Server is 900 bytes.

0

精彩评论

暂无评论...
验证码 换一张
取 消