表中设置的唯一值

时间:2010-12-16 11:13:58

标签: sql-server

假设我有一个包含三列的表:UserId TeamId IsTeamCaptain。我怎样才能确保每个TeamId的IsTeamCaptain列中只有一个'true'值?所以假设我有五个不同的UserId都属于TeamId 1,那么在这五个中只有一个'true',其余的必须是'false'。

2 个答案:

答案 0 :(得分:3)

在Set上创建唯一过滤索引(过滤索引在 SQL Server 2008 中引入)

答案 1 :(得分:0)

CREATE TABLE [dbo].[SampleTable](
        [UserID] [int] NOT NULL,
        [TeamID] [int] NOT NULL,
        [IsTeamCaptain] [bit] NOT NULL)
go

create trigger triu_SampleTable on SampleTable
instead of insert, update
as
begin
set nocount on

declare @userid int, @teamid int, @isteamcaptain bit, @counter int

declare cur cursor local fast_forward for
select userid, teamid, isteamcaptain from inserted

open cur

fetch next from cur into @userid, @teamid, @isteamcaptain
while @@fetch_status = 0
begin
if @isteamcaptain = 0
    insert into Sampletable(userid, teamid, isteamcaptain)
    values(@userid, @teamid, @isteamcaptain)
if @isteamcaptain = 1
    if exists(select * from SampleTable Where teamid = @teamid and isteamcaptain = 1)
        raiserror('Not allow to add more than 1 captain per team',16,1)
    else 
        insert into Sampletable(userid, teamid, isteamcaptain)
        values(@userid, @teamid, @isteamcaptain)

fetch next from cur into @userid, @teamid, @isteamcaptain
end

close cur
deallocate cur

end
Go

这是我们桌上的触发器