1

我有一个表access,其架构如下:

create table access (
    access_id int primary key identity,
    access_name varchar(50) not null,
    access_time datetime2 not null default (getdate()),
    access_type varchar(20) check (access_type in ('OUTER_PARTY','INNER_PARTY')),
    access_message varchar(100) not null,
)

允许的访问类型只有OUTER_PARTY and INNER_PARTY.

我想要实现的是,INNER_PARTY每个登录(用户)每天只能输入一次,但OUTER_PARTY可以记录任意次数。所以我想知道是否可以直接这样做,或者是否有一个成语来创建这种限制。

我已经检查了这个问题:Combining the UNIQUE and CHECK constraints,但无法将其应用于我的情况,因为它的目标是不同的东西。

4

2 回答 2

6

可以将过滤的唯一索引添加到表中。该索引可以基于从列中删除时间分量的计算access_time列。

create table access (
    access_id int primary key identity,
    access_name varchar(50) not null,
    access_time datetime2 not null default (SYSDATETIME()),
    access_type varchar(20) check (access_type in ('OUTER_PARTY','INNER_PARTY')),
    access_message varchar(100) not null,
    access_date as CAST(access_time as date)
)
go
create unique index IX_access_singleinnerperday on access (access_date,access_name) where access_type='INNER_PARTY'
go

似乎工作:

--these inserts are fine
insert into access (access_name,access_type,access_message)
select 'abc','inner_party','hello' union all
select 'def','outer_party','world'
go
--as are these
insert into access (access_name,access_type,access_message)
select 'abc','outer_party','hello' union all
select 'def','outer_party','world'
go
--but this one fails
insert into access (access_name,access_type,access_message)
select 'abc','inner_party','hello' union all
select 'def','inner_party','world'
go
于 2012-03-22T11:30:58.993 回答
2

不幸的是,您不能在检查约束上添加“if”。我建议使用触发器:

create trigger myTrigger
on access
instead of insert
as
begin
  declare @access_name varchar(50)
  declare @access_type varchar(20)
  declare @access_time datetime2

  select @access_name = access_name, @access_type= access_type, @access_time=access_time from inserted

  if exists (select 1 from access where access_name=@access_name and access_type=@access_type and access_time=@access_time)  begin
    --raise excetion
  end else  begin
    --insert
  end
end 

您必须格式化 @access_time 以仅考虑日期部分

于 2012-03-22T11:13:45.277 回答