Add unique constraint depending on value in SQL

后端 未结 3 779
被撕碎了的回忆
被撕碎了的回忆 2021-01-16 00:54

i have a situation where i want to add unique constaint only when there is a certain value in other field for example the table is ID CategoryName Name Value CategoryID

相关标签:
3条回答
  • 2021-01-16 01:22

    One way to achieve this would be to have two tables, one for categoryId 0 and one for the rest. You can define the uniqueness constraint on the first table, and use a view and union any time you want to use them as a single table.

    0 讨论(0)
  • 2021-01-16 01:25
    CREATE UNIQUE NONCLUSTERED INDEX [UQ_ID_CategoryName_Name, CategoryName, Name] ON TableName 
    (
        ID, CategoryName, Name
    )
    WHERE (CategoryID = 0)
    
    0 讨论(0)
  • 2021-01-16 01:30

    Create a filtered unique index on Name for CategoryID = 0.

    0 讨论(0)
提交回复
热议问题