SQL Server bit column constraint, 1 row = 1, all others 0

前端 未结 6 1908
北海茫月
北海茫月 2020-12-06 00:09

I have a bit IsDefault column. Only one row of data within the table may have this bit column set to 1, all the others must be 0.

6条回答
  •  我在风中等你
    2020-12-06 00:13

    I think the trigger is the best idea if you want to change the old default record to 0 when you insert/update a new one and if you want to make sure one record always has that value (i.e. if you delete the record with the value you would assign it to a different record). You would have to decide on the rules for doing so. These triggers can be tricky because you have to account for multiple records in the inserted and deleted tables. So if 3 records in a batch try to update to become the default record, which one wins?

    If you want to make sure the one default record never changes when someone else tries to change it, the filtered index is a good idea.

提交回复
热议问题