Add a constraint using T-SQL based on a condition

空扰寡人 提交于 2019-12-11 16:12:46

问题


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


来源:https://stackoverflow.com/questions/5116700/add-a-constraint-using-t-sql-based-on-a-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!