简体   繁体   中英

SQL Server check constraint to prevent specific duplicates

I have data structure like this:

CREATE TABLE test_Bundles 
(
   BundleId INT,
   UserId INT,
   status INT
)

INSERT INTO test_Bundles VALUES (1, 1, 1)
INSERT INTO test_Bundles VALUES (2, 1, 3)
INSERT INTO test_Bundles VALUES (3, 1, 3)
INSERT INTO test_Bundles VALUES (4, 2, 1)
INSERT INTO test_Bundles VALUES (5, 2, 3)
INSERT INTO test_Bundles VALUES (6, 2, 3)
GO

A user can only have one bundle where status=1. But they can have lots where status=2 or status=3 or status=4.

Can anyone think of a way to enforce this rule in SQL Server?

Well, you could use a trigger naturally, or you could use a unique filtered index (if you're running SQL Server 2008 or higher), ie something like:

create unique index ix_tmp 
on test_Bundles (UserId, status) where status = 1;

If you prefer to take the trigger route (which will work on any reasonable version of SQL Server), it would look something like this:

create trigger tgrTmp on test_Bundles for insert, update 
as
begin;

if exists(  select  * 
            from test_Bundles t
            join inserted i 
            on t.UserId = i.UserId
            and t.BundleId != i.BundleId
            where t.status = 1 
            and i.status = 1)
begin;
    raiserror ('unique violation',16,1);
    rollback;
end;

end;
create trigger trigPreventStatus1Duplicates
On test_Bundles for insert, update
as 
declare @errMsg varchar(200) = 
     'You cannot enter more than one status 1 bundle per user.'
set NoCount On
   begin
       if exists (Select * from inserted i 
                    join test_Bundles b 
                       on b.userId = i.userId 
                          and b.bundleId != i.bundleId
                  where b.status = 1
                  group by i.UserId
                  having count(*) > 1)
          begin
              rollback transaction
              raiserror(errMsg , 16, 1)
          end  
   end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM