2011-02-25 88 views
0

我试图根据条件添加约束条件。 例子:根据条件使用T-SQL添加约束条件

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] 

因此,有可能是将具有相同GroupKey多条记录,但我想顶多一个记录,能有EnableGroup设置为true对于一个给定GroupKey。

任何帮助表示赞赏。

+1

[T-SQL唯一约束可能重复WHERE AnotherColumn = ParticularValue](http://stackoverflow.com/questions/4097484/t-sql-unique-constraint-where-anothercolumn-particularvalue) – 2011-02-25 11:36:27

+0

刚刚意识到我链接到的问题是另一个我试图关闭并列出2其他重复... – 2011-02-25 11:49:46

回答

1

你可以使用一个检查约束与标量UDF,如:

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)) 
+0

我刚刚在2008年尝试过实例中,我插入了具有相同GroupKey的两行,并且都使用EnableGroup = 0。然后我更新了整个表以设置EnableGroup = 1,并让SQL Server让它通过。它不会让我用相同的groupid和EnableGroup添加另一行0或1,所以它部分工作,但不是100%。 – 2011-02-25 11:45:44

+0

Scalar UDF在检查约束中往往会遇到快照隔离和多行更新的问题。 – 2011-02-25 11:54:57

+0

非常感谢,看来这可以工作。 Thx再次。 – user634013 2011-03-10 20:54:01

1

你可以使用一个触发你的表:

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