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

前端 未结 6 1909
北海茫月
北海茫月 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条回答
  •  猫巷女王i
    2020-12-06 00:25

    You could apply an Instead of Insert trigger and check the value as it's coming in.

    Create Trigger TRG_MyTrigger
    on MyTable
    Instead of Insert
    as
    Begin
    
      --Check to see if the row is marked as active....
      If Exists(Select * from inserted where IsDefault= 1)
      Begin
         Update Table Set IsDefault=0 where ID= (select ID from inserted);
    
         insert into Table(Columns)
         select Columns from inserted
      End
    
    End
    

    Alternatively you could apply a unique constraint on the column.

提交回复
热议问题