Add a constraint using T-SQL based on a condition

2019-09-02 02:40发布

问题:

I am trying to add a constraint based on a condition. Example:

CREATE TABLE dbo.TestTable(
        [DbKey] [uniqueidentifier] NOT NULL,
        [GroupKey] [uniqueidentifier] NOT NULL,
        [EnableGroup] bit NOT NULL
        CONSTRAINT [TestTable_PK] PRIMARY KEY CLUSTERED 
        (
            [DbKey] ASC
        )
)ON [PRIMARY]

So, there could be multiple records that would have the same GroupKey, but I want that at most one record, could have the EnableGroup set to true for a given GroupKey.

Any help is appreciated.

回答1:

You could use a check constraint with a scalar UDF, like:

go
create function dbo.EnabledGroupCount(
    @GroupKey uniqueidentifier)
returns int as begin
    return (
    select COUNT(*) from TestTable where GroupKey = @GroupKey and EnableGroup = 1
    )
end
go
alter table TestTable add constraint chk_TestTable 
    check (dbo.EnabledGroupCount(GroupKey) in (0,1))


回答2:

You could use a trigger for your table:

if exists(select 1
            from inserted i
           where exists(select 1
                          from dbo.TestTable tt
                         where tt.GroupKey = i.GroupKey
                           and tt.EnableGroup = 1
                         group by tt.GroupKey
                        having count(*) > 1))
begin
   raiserror('Some meaningful error message here.')
   rollback
   return
end