开发者

Sql Server 2008 unique columns by condition

Let's assume I have following table in the database:

Id ProductId ColorId IsDele开发者_开发百科ted
1  1         1       1
2  1         1       0
3  2         3       0

I want to make ProductId and ColorId columns unique but only for those rows where IsDeleted = 0. How do I can achieve this requirement?

I know, I can create a constraint which will call a stored function. And stored function will try to find an entry with the same values. But I think it is to complex way. May be there is a better decision...


In SQL Server 2008 and newer, you can take advantage of filtered indices to achieve this:

CREATE NONCLUSTERED UNIQUE INDEX ProductColor
   ON dbo.YourTable(ProductID, ColorID)
   WHERE IsDeleted = 0;

See the Filtered Index Design Guidelines for some more background and best practices.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜