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エントリはログイン (ユーザー) ごとに 1 日 1 回だけにする必要があることですが、OUTER_PARTY記録は何度でも行うことができます。それで、直接それを行うことが可能かどうか、またはこの種の制限を作成するイディオムがあるかどうか疑問に思っていました.

私はこの質問をチェックしました: UNIQUE と CHECK の制約を組み合わせていますが、別のことを目指していたため、私の状況に適用できませんでした。

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 に答える